package kr.co.hanwha.hifive.admin.admin;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.admin.admin.adapter.AdminVersionListAdapter;
import kr.co.hanwha.hifive.admin.network.AdminNetworkUtil;
import kr.co.hanwha.hifive.admin.network.model.AdminVersionCvData;
import kr.co.hanwha.hifive.admin.network.model.AdminVersionCvRoot;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.data.model.BaseData;
import kr.co.hanwha.hifive.data.model.MemberInfoData;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
import kr.co.hanwha.hifive.dialog.HFDefaultDialog;
import kr.co.hanwha.hifive.dialog.HFSingleDialog;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkCallback;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkError;
import kr.co.hanwha.hifive.util.HFActivityUtil;

public class AdminVersionListActivity extends BaseActivity {
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;

    private AdminVersionListAdapter mAdapter;

    private final int REQUEST_ADD_VERSION = 1000;

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_admin_version_list;
    }

    @Override
    protected BaseToolbarType isToolbarStyle() {
        return BaseToolbarType.NONE;
    }

    @Override
    protected BaseAnimationType isShowActivityAnimation() {
        return BaseAnimationType.RIGHT;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAdapter = new AdminVersionListAdapter(onAdminVersionListListener);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshListener(onRefreshListener);

        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        findViewById(R.id.back_imageButton).setOnClickListener(onClickListener);
        findViewById(R.id.add_textView).setOnClickListener(onClickListener);

        initData(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ADD_VERSION && resultCode == RESULT_OK) {
            initData(true);
        } else
            super.onActivityResult(requestCode, resultCode, data);
    }

    private final Comparator<AdminVersionCvData> sort = new Comparator<AdminVersionCvData>() {
        @Override
        public int compare(AdminVersionCvData o1, AdminVersionCvData o2) {
            return o2.getVersion().compareTo(o1.getVersion());
        }
    };

    private void initData(final boolean needLoading) {
        String encryption_member_id = MemberDataRepository.getInstance().getEncryptionMemberId();
        AdminNetworkUtil networkUtil = new AdminNetworkUtil();
        networkUtil.requestClientVersionList(this, encryption_member_id, new HanwhaNetworkCallback<AdminVersionCvRoot>() {
            @Override
            public void onSuccess(final AdminVersionCvRoot response) {
                if (response == null) return;

                Collections.sort(response.getListCvInfo(), sort);
                mAdapter.addItems(response.getListCvInfo());
                mAdapter.notifyDataAll();
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                showAlert(error, new HFSingleDialog.OnDialogCallback() {
                    @Override
                    public void onPositive() {

                    }
                });
            }

            @Override
            public void onPreExecute() {
                if (needLoading)
                    showLoadingDialog(true);
            }

            @Override
            public void onPostExecute() {
                showLoadingDialog(false);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**************************************************
     * Support methods
     **************************************************/
    public void doDelete(int id) {
        String encryption_member_id = MemberDataRepository.getInstance().getEncryptionMemberId();
        AdminNetworkUtil networkUtil = new AdminNetworkUtil();
        networkUtil.requestClientVersionDelete(this, encryption_member_id,
                id,
                new HanwhaNetworkCallback<BaseData>() {
                    @Override
                    public void onSuccess(final BaseData response) {
                        showToast("버전 정보가 삭제되었습니다.");
                        initData(true);
                    }

                    @Override
                    public void onFailure(HanwhaNetworkError error) {
                        showAlert(error, new HFSingleDialog.OnDialogCallback() {
                            @Override
                            public void onPositive() {

                            }
                        });
                    }

                    @Override
                    public void onPreExecute() {
                        showLoadingDialog(true);
                    }

                    @Override
                    public void onPostExecute() {
                        showLoadingDialog(false);
                    }
                });
    }

    /**************************************************
     * View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.back_imageButton:
                    finish();
                    break;
                case R.id.add_textView:
                    Intent intent = new Intent(AdminVersionListActivity.this, AdminVersionAddActivity.class);
                    startActivityForResult(intent, REQUEST_ADD_VERSION);
                    break;
            }
        }
    };

    /**************************************************
     * SwipeRefreshLayout.OnRefreshListener
     **************************************************/
    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            initData(false);
        }
    };

    /**************************************************
     * AdminVersionListAdapter.OnAdminVersionListListener
     **************************************************/
    AdminVersionListAdapter.OnAdminVersionListListener onAdminVersionListListener = new AdminVersionListAdapter.OnAdminVersionListListener() {
        @Override
        public void onDeleteClicked(final int id) {
            showAlert("삭제", "삭제하시겠습니까?", new HFDefaultDialog.OnDialogCallback() {
                @Override
                public void onNegative() {

                }

                @Override
                public void onPositive() {
                    doDelete(id);
                }
            });
        }

        @Override
        public void onEditClicked(AdminVersionCvData data) {
            Intent intent = new Intent(AdminVersionListActivity.this, AdminVersionAddActivity.class);
            intent.putExtra("IS_EDIT", true);


            intent.putExtra("id", data.getId());
            intent.putExtra("platform_type", data.getPlatform_type());
            intent.putExtra("version", data.getVersion());
            intent.putExtra("string_bundle", data.getString_bundle());
            intent.putExtra("is_forced", data.isIs_forced());
            intent.putExtra("update_notice", data.getUpdate_notice());
            intent.putExtra("update_url", data.getUpdate_url());
            intent.putExtra("released_at", data.getReleased_at());
            startActivityForResult(intent, REQUEST_ADD_VERSION);
        }

        @Override
        public void onUrlLinkClicked(String url) {
            try {
                HFActivityUtil.startUrl(AdminVersionListActivity.this, url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
