package com.ntels.onecable.admin.view.mainmore;

import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.AppConfig;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.c_interface.ListInterface;
import com.ntels.onecable.admin.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.util.recyclerview.DividerItemDecoration;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.ntels.onecable.admin.view.dialog.PushDialog;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;

public class HomehubList extends CustomActivity implements CustomDialog.OnMsgAlterToResult, ListInterface {

    private static final int MSG_COM_G_DEVICE_LIST = 1;

    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Activity mActivity;
    private HomehubListAdapter mDataAdapter;
    @BindView(R.id.swiperefreshlayout) SwipeRefreshLayout mSwipeRefreshLayout;
    private GridLayoutManager mGlmList;
    private LinearLayoutManager mLlmList;
    private Toolbar mToolbar;
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<>();
    private boolean mLoading = false;
    private boolean mIsListHeader = false;
    private int mType = 0;
    private int mListColumnsCnt = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = HomehubList.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);
        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.homehub_list, null);

        this.setContentView(viewToLoad);

        ButterKnife.bind(this);

        setToolbar();

        displayListView();
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }

    @OnClick({R.id.llBtn1})
    public void onClick() {
        onBackPressed();
    }

    /**
     * Process list reload.
     */
    @Override
    public void onListReload() {

    }

    /**
     * Process logout.
     */
    @Override
    public void onLogout() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_HOMEHUB:
                    if (data == null) {
                        return;
                    }
                    Boolean isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICE_LIST), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEHUB:
                    if (data == null) {
                        return;
                    }
                    Boolean isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICE_LIST), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Process action(ex> 기기 추가, 기기 삭제, 기기 상세보기...)
     *
     * @param iCallType Action type
     * @param iPosition Data index
     */
    @Override
    public void onCallAction(int iCallType, int iPosition) {
        mIntent = new Intent(mActivity, Homehub.class);
        mIntent.putExtra(Constants.EXTRA_DEVICE_ID, mUtil.null2string(mTotalList.get(iPosition).get(Constants.KEY_DEVICE_ID)));
        mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_HOMEHUB);
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICE_LIST:
                    sendGetHomehubList();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        mToolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, mToolbar);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1)
                .setText(mUtil.getString(mActivity, R.string.layout_homehub_list_01));
    }

    /**
     * UI display.
     */
    private void displayListView() {

        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light,
                android.R.color.holo_green_light, android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if (!mDataAdapter.getListCheck()) {
                    if (!mLoading) {
                        mLoading = true;
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICE_LIST), Constants.HANDLER_DELAY_MILLIS);
                    }
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);
        mLoading = false;

        mDataAdapter = new HomehubListAdapter(0, R.layout.row_homehub_list, 0, mTotalList, this);
        RecyclerView recyclerView = (RecyclerView) mActivity.findViewById(R.id.rcvList);
        recyclerView.setHasFixedSize(true);
        mListColumnsCnt = 1;
        if (mListColumnsCnt == 1) {
            mLlmList = new LinearLayoutManager(mActivity);
            recyclerView.setLayoutManager(mLlmList);
        } else {
            mGlmList = new GridLayoutManager(mActivity, mListColumnsCnt, GridLayoutManager.VERTICAL, false);
            mGlmList.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {

                    int positionType = mDataAdapter.getItemViewType(position);
                    int totalCount = mDataAdapter.getItemCount();
                    int valueCount = mDataAdapter.getItemCount();
                    if (mIsListHeader) {
                        valueCount = totalCount - 1;
                    }

                    if (positionType == mDataAdapter.TYPE_HEADER) {
                        return mGlmList.getSpanCount();
                    } else {
                        return mDataAdapter.getItemViewType(position) == 1 ? 1
                                : (valueCount % mListColumnsCnt == 1 ? mGlmList.getSpanCount() : 1);
                    }
                }
            });
            recyclerView.setLayoutManager(mGlmList);
        }
        recyclerView.addItemDecoration(new DividerItemDecoration(mActivity, R.drawable.color_line_01, true, false));

        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(mDataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        recyclerView.setAdapter(scaleAdapter);

        mLoading = true;
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICE_LIST), Constants.HANDLER_DELAY_MILLIS);
    }

    /**
     * mSwipeRefreshLayout enable/disable.
     *
     * @param isEnable true or false
     */
    private void setRefresh(boolean isEnable) {

        if (isEnable) {
            mSwipeRefreshLayout.setEnabled(true);
        } else {
            mSwipeRefreshLayout.setEnabled(false);
        }
    }

    /**
     * Dialog click listener method.
     *
     * @param msgId     Message constant
     * @param btnResult Selected button index (Positive - 1, Negative - 2)
     */
    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    mActivity.onBackPressed();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 홈허브 목록 조회 요청.
     */
    private void sendGetHomehubList() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity, !mSwipeRefreshLayout.isRefreshing());

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetHomehubList(result);
                }
            });
            httpSend.getHomehubList("");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendGetHomehubList()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultGetHomehubList(Response response) {

        try {
            if (response.getStatusCode() == 200) {
                Dlog.v(response.getContent());
                mTotalList.clear();
                mTotalList = mUtil.jsonToArrayListMap(response.getContent());

                if (mTotalList.size() > 0) {
                    mSwipeRefreshLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTotalList.size() == 0) {
                        mSwipeRefreshLayout.setVisibility(View.GONE);
                    }
                }
                mLoading = false;
                mDataAdapter.setData(mTotalList);
                mDataAdapter.notifyDataSetChanged();
                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }
}
