/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.onecable.view.rules;

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

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
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 android.view.ViewGroup;
import android.widget.Toast;

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

import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;

/**
 * 1. ClassName :   FragmentRules
 * 2. FileName  :   FragmentRules.java
 * 3. Package   :   com.ntels.onecable.view.rules
 * 4. Date      :   2016-11-29
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 */
public class FragmentRules extends Fragment implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult,
        ListInterface {

    private static final int MSG_COM_G_RULES = 1;
    private static final int MSG_COM_D_RULES_HOMEGRP_RULE_ID = 2;
    private static final int MSG_COM_P_RULES_STATUS = 3;
    Boolean isReload = false;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    /*툴바 관련*/
    private Toolbar mToolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<HashMap<String, Object>>();
    private int type = 0;
    /*리스트 관련*/
    private FragmentRulesAdapter mDataAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private GridLayoutManager mGridLayoutManager;
    private DialogCustomList.Builder mDialogListBuilder;
    private boolean mLoading = false;
    private boolean mIsListHeader = false;
    private int mListColumnsCnt = 1;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private MainInterface mCallback;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mSearchType = "";
    private String mRuleId = "";
    private String mMaxRuleId = "";
    private String mMinRuleId = "";
    private int mSelectPosition = -1;
    private String mActivityName = "";

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            mCallback = (MainInterface) activity;
        } catch (ClassCastException ex) {
            throw new ClassCastException(activity.toString() + " must implement MainInterface");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Dlog.v("onCreate()");
    }

    @Override
    public void onStop() {

        super.onStop();
        Dlog.v("onStop()");
//        GoogleAnalytics.getInstance(mActivity).reportActivityStop(mActivity);
    }

    @Override
    public void onStart() {

        super.onStart();
        Dlog.v("onStart()");
//        GoogleAnalytics.getInstance(mActivity).reportActivityStart(mActivity);
    }

    @Override
    public void onPause() {

        super.onPause();
        Dlog.v("onPause()");
    }

    @Override
    public void onResume() {

        super.onResume();
        Dlog.v("onResume()");
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Dlog.v("onDestroy()");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_rules, container, false);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        Dlog.v("onActivityCreated().");
        Dlog.v(savedInstanceState == null ? "true" : "false");

        mActivity = getActivity();
        mActivityName = "Rules_List";
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        mUtil.callActGoogleAnalytics(mActivityName);
        setToolbar();

        displayListView();
    }

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

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

        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1)
                .setText(mUtil.getString(mActivity, R.string.layout_rules_01));
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText("");
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle3)
                .setText(mUtil.getString(mActivity, R.string.layout_rules_02));
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setText("");

        mUtil.getView(mToolbar, R.id.btnToolbarClose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mUtil.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                mDataAdapter.setListCheck(false);
                setRefresh(true);
                if (isReload) {
                    onListReload();
                } else {
                    mDataAdapter.notifyDataSetChanged();
                }
            }
        });
        mUtil.getView(mToolbar, R.id.btnToolbarMore).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ArrayList<HashMap<String, Object>> alMenuList = new ArrayList<HashMap<String, Object>>();
                alMenuList.add(mUtil.getPopMenu(6));
                if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
                    alMenuList.add(mUtil.getPopMenu(11));
                    if (mTotalList.size() > 0) {
                        alMenuList.add(mUtil.getPopMenu(18));
                    }
                }
                msgAlertList(alMenuList);
            }
        });
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 타이틀과 리스트를 보여준다.
     */
    public void setHomeHubStateAll() {

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 다른 타이틀을 보여준다.
     */
    public void setHomeHubStateTitle() {

        if (mAppConfig.getCtrtGroupId().equals("")) {
            //홈그룹 없을경우
            mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
            mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
            mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
            mUtil.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
            if (mDialogListBuilder != null) {
                mDialogListBuilder.create().dismiss();
            }
        } else {
            //홈그룹 있을경우
            if (!mAppConfig.getIsCtrtGroupHomehub()){
                //홈그룹은 있고 홈허브가 없는경우
                mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.GONE);
                mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.VISIBLE);
                mUtil.getTextView(mToolbar, R.id.tvToolbarHomeHub)
                        .setText(mUtil.getString(mActivity, R.string.layout_homehub_delete));
                mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                mUtil.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                if (mDialogListBuilder != null) {
                    mDialogListBuilder.create().dismiss();
                }
            } else {
                //                mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                if (mAppConfig.getSelectCtrtGroupHomehubOnlineState().equals("OFF")) {
                    //홈그룹은 있고 홈허브가 오프라인인경우
                    mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.GONE);
                    mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.VISIBLE);
                    mUtil.getTextView(mToolbar, R.id.tvToolbarHomeHub)
                            .setText(mUtil.getString(mActivity, R.string.layout_homehub_offline));
                } else {
                    //홈그룹은 있고 홈허브가 온라인인 경우
                    mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
                    mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 다른 리스트를 보여준다.
     *
     * @return : 리스트 갱신했는지 여부
     */
    public boolean setHomeHubStateList() {

        Boolean isListLoad = false;
        mSwipeRefreshLayout.setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Master).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Guest).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Master).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Guest).setVisibility(View.GONE);

        mUtil.getView(mActivity, R.id.llNoHub_NoHome_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Master_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Guest_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Master_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Guest_Smartcity).setVisibility(View.GONE);
        if (mAppConfig.getCtrtGroupId().equals("")) {
            //홈그룹 없을경우
//            mUtil.getView(mActivity, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
            mDataAdapter.setListCheck(false);
            mDataAdapter.notifyDataSetChanged();
            setRefresh(false);
        } else {
            //홈그룹 있을경우
            if (!mAppConfig.getIsCtrtGroupHomehub()){
                //홈그룹은 있고 홈허브가 없는경우
                if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
//                    mUtil.getView(mActivity, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
                    mDataAdapter.setListCheck(false);
                    mDataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                } else {
                    mUtil.getView(mActivity, R.id.llNoHub_Guest).setVisibility(View.VISIBLE);
                    mDataAdapter.setListCheck(false);
                    mDataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                }
            } else {
                if (mTotalList.size() > 0) {
                    mSwipeRefreshLayout.setVisibility(View.VISIBLE);
                } else {
                    if (!mLoading) {
                        if (!mSwipeRefreshLayout.isRefreshing()) {
                            if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
                                mUtil.getView(mActivity, R.id.llNodata_Master).setVisibility(View.VISIBLE);
                                mUtil.getTextView(mActivity, R.id.tvNodata_Master_Title)
                                        .setText(R.string.layout_nodata_desc_05);
                            } else {
//                                mUtil.getView(mActivity, R.id.llNodata_Guest).setVisibility(View.VISIBLE);
//                                mUtil.getTextView(mActivity, R.id.tvNodata_Guest_Title)
//                                        .setText(R.string.layout_nodata_desc_03);
                            }
                        }
                    }
                    mDataAdapter.setListCheck(false);
                }
                if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
                    mDataAdapter.setFooterVisible(true);
                } else {
                    mDataAdapter.setFooterVisible(false);
                }
                mDataAdapter.notifyDataSetChanged();
                isListLoad = true;
            }
        }
        return isListLoad;
    }

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

        mUtil.getView(mActivity, R.id.llNodata_Master).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llNoHub_Master).setOnClickListener(this);
        mUtil.getViewUnderline(mActivity, R.id.tvWidthdraw);
        mUtil.getView(mActivity, R.id.tvWidthdraw).setOnClickListener(this);
        mUtil.getViewUnderline(mActivity, R.id.tvConnect);

        mTotalList.clear();

        mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swiperefreshlayou);
        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) {
                        onListReload();
                    }
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        boolean isListFooter = true;
        boolean isListFooterVisible = true;
        mDataAdapter = new FragmentRulesAdapter(mActivity, R.layout.row_rules_list, R.layout.row_rules_list,
                R.layout.row_footer_rules_list, mTotalList, this);
        mDataAdapter.setFooterCheck(isListFooter);
        mDataAdapter.setFooterVisible(isListFooterVisible);

        RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.rcvList);
        recyclerView.setHasFixedSize(true);
        mListColumnsCnt = 1;
        if (mListColumnsCnt == 1) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
            recyclerView.setLayoutManager(linearLayoutManager);
        } else {
            mGridLayoutManager = new GridLayoutManager(mActivity, mListColumnsCnt,
                    GridLayoutManager.VERTICAL, false);
            mGridLayoutManager.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 mGridLayoutManager.getSpanCount();
                    } else {
                        return 1;
//                        return mDataAdapter.getItemViewType(position) == 1 ? 1 :
//                                (valueCount % mListColumnsCnt == 1 ? mGridLayoutManager.getSpanCount() : 1);
                    }
                }
            });
            recyclerView.setLayoutManager(mGridLayoutManager);
        }
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
                R.drawable.color_line_01));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(mDataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        recyclerView.setAdapter(scaleAdapter);

        setHomeHubStateTitle();
        if (!mLoading) {
            onListReload();
        }
    }

    /**
     * mSwipeRefreshLayout enable/disable.
     *
     * @param isRefresh : true - enable, false - disable
     */
    private void setRefresh(boolean isRefresh) {

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

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llNoHub_Master:
                mCallback.onHomehubStart();
                break;
            case R.id.tvWidthdraw:
                mCallback.onHomeMemberWidthdraw();
                break;
            case R.id.llNodata_Master:
                goRulesEdit();
                break;
            default:
                break;
        }
    }

    /**
     * 홈 규칙 상태 변경(해당 규칙의 상태를 변경한다) 요청.
     */
    private void sendPutRuleStatus() {

        try {
            HttpSend httpSend;

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

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

                    resultPutRuleStatus(result);
                }
            });
            String ruleId = mUtil.null2string(mTotalList.get(mSelectPosition).get(Constants.KEY_RULE_ID));
            String useYn = mUtil.null2string(mTotalList.get(mSelectPosition).get(Constants.KEY_USE_YN));
            String statusCode = "";

            if (useYn.equals("Y")) {
                statusCode = "03";
            } else if (useYn.equals("N")) {
                statusCode = "02";
            }
            httpSend.putRuleStatus(ruleId, statusCode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈 규칙 상태 변경(해당 규칙의 상태를 변경한다) 요청 결과.
     *
     * @param result : 결과 data
     */
    private void resultPutRuleStatus(Response result) {

        try {
            if (result.getStatusCode() == 200) {
//                onListReload();
                String activeCount = "";
                String inactiveCount = "";
                if ("Y".equals(mTotalList.get(mSelectPosition).get(Constants.KEY_USE_YN))) {
                    mTotalList.get(mSelectPosition).put(Constants.KEY_USE_YN, "N");
                    // 타이틀 활성 카운트 수정
                    activeCount = mUtil.null2string(Integer.valueOf(
                            mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).getText().toString()) - 1);
                    inactiveCount = mUtil.null2string(Integer.valueOf(
                            mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).getText().toString()) + 1);
                } else {
                    mTotalList.get(mSelectPosition).put(Constants.KEY_USE_YN, "Y");
                    // 타이틀 비활성 카운트 수정
                    activeCount = mUtil.null2string(Integer.valueOf(
                            mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).getText().toString()) + 1);
                    inactiveCount = mUtil.null2string(Integer.valueOf(
                            mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).getText().toString()) - 1);
                }
                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText(activeCount);
                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setText(inactiveCount);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if (resultCode.equals("401")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 홈 규칙 목록 조회(홈의 규칙 목록을 조회한다) 요청.
     */
    private void sendGetRules() {

        try {
            HttpSend httpSend;

            if (mSearchType.equals("D")) {
                httpSend = new HttpSend(mActivity, false);
            } else {
                httpSend = new HttpSend(mActivity, !mSwipeRefreshLayout.isRefreshing());
            }

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

                    resultGetRules(result);
                }
            });
            httpSend.getRules(mRuleId, mSearchType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈 규칙 목록 조회(홈의 규칙목록을 조회한다) 요청.
     *
     * @param result : 결과 data
     */
    private void resultGetRules(Response result) {

        try {
            // 더보기 조회인경우와 최초 조회인경우
            if (mSearchType.equals("D")) {
                HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                hmTemp.put(Constants.KEY_MORE_YN, "N");
                mTotalList.remove(mTotalList.size() - 1);
                mDataAdapter.notifyDataSetChanged();
            } else {
                mTotalList.clear();
            }
            if (result.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());

                String activeCount = mUtil.null2string(joResult.get(Constants.KEY_ACTIVE_COUNT));
                String inactiveCount = mUtil.null2string(joResult.get(Constants.KEY_INACTIVE_COUNT));
                String rules = mUtil.null2string(joResult.get(Constants.KEY_RULES));

                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText(activeCount);
                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setText(inactiveCount);

                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(rules);
                if (alList.size() > 0) {
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp = alList.get(row);
                        String ruleId = mUtil.null2string(hmTemp.get(Constants.KEY_RULE_ID));
                        if (mMinRuleId.equals("")) {
                            mMinRuleId = ruleId;
                        } else if (mUtil.str2long(mMinRuleId) > mUtil.str2long(ruleId)) {
                            mMinRuleId = ruleId;
                        }
                        if (mUtil.str2long(mMaxRuleId) < mUtil.str2long(ruleId)) {
                            mMaxRuleId = ruleId;
                        }
                        mTotalList.add(hmTemp);
                    }

                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    hmTemp.put(Constants.KEY_MORE_YN, "N");
                    mTotalList.add(hmTemp);
                } else {
                    if (mSearchType.equals("D")) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp.put(Constants.KEY_MORE_YN, "N");
                        mTotalList.add(hmTemp);
                    }
                }
                mLoading = false;
                setHomeHubStateAll();
                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if (resultCode.equals("401")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 홈 규칙 삭제(해당 규칙을 삭제한다) 요청.
     */
    private void sendDeleteRule() {

        try {
            HttpSend httpSend;

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

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

                    resultDeleteRule(result);
                }
            });
            String homegrpRuleId = mUtil.null2string(mTotalList.get(mSelectPosition).get(Constants.KEY_RULE_ID));
            httpSend.deleteRule(homegrpRuleId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈 규칙 삭제(해당 규칙을 삭제한다) 요청 결과.
     *
     * @param result : 결과 data
     */
    private void resultDeleteRule(Response result) {

        try {
            if (result.getStatusCode() == 200) {
                isReload = true;
                if ("Y".equals(mTotalList.get(mSelectPosition).get(Constants.KEY_USE_YN))) {
                    // 타이틀 활성 카운트 수정
                    String activeCount = mUtil.null2string(Integer.valueOf(
                            mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).getText().toString()) - 1);
                    mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText(activeCount);
                } else {
                    // 타이틀 비활성 카운트 수정
                    String inactiveCount = mUtil.null2string(Integer.valueOf(
                            mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).getText().toString()) - 1);
                    mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setText(inactiveCount);
                }
                mTotalList.remove(mSelectPosition);
                mDataAdapter.notifyDataSetChanged();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if (resultCode.equals("401")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    @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) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), Constants.HANDLER_DELAY_MILLIS);
                } else {
//                    mActivity.onBackPressed();
                }
                break;
            case Constants.MSG810:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_D_RULES_HOMEGRP_RULE_ID),
                            Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG818:
                if (btnResult == 1) {
                    String homegrpRuleId = mUtil.null2string(mTotalList.get(mSelectPosition)
                            .get(Constants.KEY_HOMEGRP_RULE_ID));
                    Intent intent = new Intent(mActivity, RulesEdit.class);
                    intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                    intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, homegrpRuleId);
                    mUtil.callActivityForResult(mActivity, intent, Constants.ACT_RULES_EDIT);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 메뉴 선택 시 처리.
     *
     * @param list : 메뉴 리스트
     */
    private void msgAlertList(ArrayList<HashMap<String, Object>> list) {

        try {
            mDialogListBuilder = new DialogCustomList.Builder(mActivity);
            mDialogListBuilder.setList(list);
            mDialogListBuilder.setPositiveButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                    Dlog.v("which = " + which);
                    switch (which) {
                        case 1:
                            break;
                        case 2:
                            break;
                        case 3:
                            break;
                        case 4:
                            break;
                        case 5:
                            break;
                        case 6:
                            onListReload();
                            break;
                        case 7:
                            break;
                        case 8:
                            break;
                        case 9:
                            break;
                        case 10:
                            break;
                        case 11:
                            goRulesEdit();
                            break;
                        case 12:
                            break;
                        case 15:
                            break;
                        case 16:
                            break;
                        case 17:
                            break;
                        case 18:
                            mUtil.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            mDataAdapter.setListCheck(true);
                            mDataAdapter.notifyDataSetChanged();
                            setRefresh(false);
                            break;
                        default:
                            break;
                    }
                }
            });
            mDialogListBuilder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Dlog.v("which = " + which);
                    dialog.dismiss();
                }
            });
            mDialogListBuilder.create().show();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * RulesEdit activity로 이동.
     */
    public void goRulesEdit() {

        Intent intent = new Intent(mActivity, RulesEdit.class);
        intent.putExtra(Constants.EXTRA_CALL_TYPE, "1");
        mUtil.callActivityForResult(mActivity, intent, Constants.ACT_RULES_EDIT);
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_RULES_DETAIL:
                    if (data == null) {
                        return;
                    }
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_RULES_EDIT:
                    if (data == null) {
                        return;
                    }
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_RULES_DETAIL:
                    if (data == null) {
                        return;
                    }
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_RULES_EDIT:
                    if (data == null) {
                        return;
                    }
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onListReload() {

        mLoading = true;
        mSearchType = "";
        mRuleId = "";
        if (setHomeHubStateList()) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES), Constants.HANDLER_DELAY_MILLIS);
        }
    }

    @Override
    public void onLogout() {
    }

    @Override
    public void onCallAction(int callType, int position) {

        if (callType == 0) {
            mUtil.callBtnGoogleAnalytics(mActivityName, "Create_Rules", "");
            //추가하기
            goRulesEdit();
        } else if (callType == 1) {
            mUtil.callBtnGoogleAnalytics(mActivityName, "ViewDetail_Rules", "");
            // 상세보기
            String ruleId = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_RULE_ID));
            Intent intent = new Intent(mActivity, RulesDetail.class);
            intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, ruleId);
            mUtil.callActivityForResult(mActivity, intent, Constants.ACT_RULES_DETAIL);
        } else if (callType == 2) {
            mUtil.callBtnGoogleAnalytics(mActivityName, "Delete_Rules", "");
            mSelectPosition = position;
            mCustomDialog.msgAlert(mActivity, Constants.MSG810, R.string.MSG_TITLE_003,
                    mUtil.getString(mActivity, R.string.layout_delete), mUtil.getString(mActivity, R.string.layout_cancel));
        } else if (callType == 3) {
            mUtil.callBtnGoogleAnalytics(mActivityName, "Active_Rules", "");
            // 활성화 비활성화
            mSelectPosition = position;
            String useYn = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_USE_YN));
            if (useYn.equals("Y")) {
                mUtil.setVibrator(100);
                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG808), Toast.LENGTH_SHORT);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_RULES_STATUS), Constants.HANDLER_DELAY_MILLIS);
            } else if (useYn.equals("N")) {
                mUtil.setVibrator(100);
                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG809), Toast.LENGTH_SHORT);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_RULES_STATUS), Constants.HANDLER_DELAY_MILLIS);
            } else if (useYn.equals("X")) {
                mCustomDialog.msgAlert(mActivity, Constants.MSG818, R.string.MSG_TITLE_000,
                        mUtil.getString(mActivity, R.string.MSG_BTN_EDIT),
                        mUtil.getString(mActivity, R.string.MSG_BTN_CANCEL));
            }
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_G_RULES:
                    sendGetRules();
                    break;
                case MSG_COM_D_RULES_HOMEGRP_RULE_ID:
                    sendDeleteRule();
                    break;
                case MSG_COM_P_RULES_STATUS:
                    //dialog_show();
                    sendPutRuleStatus();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
