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

package com.ntels.onecable.view.rules;

import com.google.android.gms.analytics.GoogleAnalytics;

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_HOMEGRP_RULE_ID_STATUS = 3;
    Boolean isReload = false;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    /*툴바 관련*/
    private Toolbar toolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<HashMap<String, Object>>();
    private int type = 0;
    /*리스트 관련*/
    private FragmentRulesAdapter dataAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private GridLayoutManager gridLayoutManager;
    private DialogCustomList.Builder dialogListBuilder;
    private boolean loading = false;
    private boolean isListHeader = false;
    private int listColumnsCnt = 1;
    /*공통*/
    private Activity act;
    private AppConfig appConfig;
    private MainInterface callback;
    private Util util = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private String searchType = "";
    private String ruleId = "";
    private String maxRuleId = "";
    private String minRuleId = "";
    private int selectPosition = -1;
    private String activityName = "";

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            callback = (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(act).reportActivityStop(act);
    }

    @Override
    public void onStart() {

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

    @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");

        act = getActivity();
        activityName = "Rules_List";
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        util.callActGoogleAnalytics(activityName);
        setToolbar();

        displayListView();
    }

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

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

        util.getTextView(toolbar, R.id.tvToolbarTitle1)
                .setText(util.getString(act, R.string.layout_rules_01));
        util.getTextView(toolbar, R.id.tvToolbarTitle2).setText("");
        util.getTextView(toolbar, R.id.tvToolbarTitle3)
                .setText(util.getString(act, R.string.layout_rules_02));
        util.getTextView(toolbar, R.id.tvToolbarTitle4).setText("");

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

                util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                util.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                dataAdapter.setListCheck(false);
                setRefresh(true);
                if (isReload) {
                    onListReload();
                } else {
                    dataAdapter.notifyDataSetChanged();
                }
            }
        });
        util.getView(toolbar, 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(util.getPopMenu(6));
                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    alMenuList.add(util.getPopMenu(11));
                    if (alTotalList.size() > 0) {
                        alMenuList.add(util.getPopMenu(18));
                    }
                }
                msgAlertList(alMenuList);
            }
        });
    }

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

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

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

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

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

        Boolean isListLoad = false;
        swipeRefreshLayout.setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Master).setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Guest).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Master).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Guest).setVisibility(View.GONE);

        util.getView(act, R.id.llNoHub_NoHome_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Master_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Guest_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Master_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Guest_Smartcity).setVisibility(View.GONE);
        if (appConfig.getCtrtGroupId().equals("")) {
            //홈그룹 없을경우
            util.getView(act, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
            dataAdapter.setListCheck(false);
            dataAdapter.notifyDataSetChanged();
            setRefresh(false);
        } else {
            //홈그룹 있을경우
            if (!appConfig.getIsHomegrpHomehub()){
                //홈그룹은 있고 홈허브가 없는경우
                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    util.getView(act, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
                    dataAdapter.setListCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                } else {
                    util.getView(act, R.id.llNoHub_Guest).setVisibility(View.VISIBLE);
                    dataAdapter.setListCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                }
            } else {
                if (alTotalList.size() > 0) {
                    swipeRefreshLayout.setVisibility(View.VISIBLE);
                } else {
                    if (!loading) {
                        if (!swipeRefreshLayout.isRefreshing()) {
                            if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                                util.getView(act, R.id.llNodata_Master).setVisibility(View.VISIBLE);
                                util.getTextView(act, R.id.tvNodata_Master_Title)
                                        .setText(R.string.layout_nodata_desc_05);
                            } else {
                                util.getView(act, R.id.llNodata_Guest).setVisibility(View.VISIBLE);
                                util.getTextView(act, R.id.tvNodata_Guest_Title)
                                        .setText(R.string.layout_nodata_desc_03);
                            }
                        }
                    }
                    dataAdapter.setListCheck(false);
                }
                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    dataAdapter.setFooterVisible(true);
                } else {
                    dataAdapter.setFooterVisible(false);
                }
                dataAdapter.notifyDataSetChanged();
                isListLoad = true;
            }
        }
        return isListLoad;
    }

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

        util.getView(act, R.id.llNodata_Master).setOnClickListener(this);
        util.getView(act, R.id.llNoHub_Master).setOnClickListener(this);
        util.getViewUnderline(act, R.id.tvWidthdraw);
        util.getView(act, R.id.tvWidthdraw).setOnClickListener(this);
        util.getViewUnderline(act, R.id.tvConnect);

        alTotalList.clear();

        swipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swiperefreshlayou);
        swipeRefreshLayout.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);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if (!dataAdapter.getListCheck()) {
                    if (!loading) {
                        onListReload();
                    }
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        boolean isListFooter = true;
        boolean isListFooterVisible = true;
        dataAdapter = new FragmentRulesAdapter(act, R.layout.row_rules_list, R.layout.row_rules_list,
                R.layout.row_footer_rules_list, alTotalList, this);
        dataAdapter.setFooterCheck(isListFooter);
        dataAdapter.setFooterVisible(isListFooterVisible);

        RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.rcvList);
        recyclerView.setHasFixedSize(true);
        listColumnsCnt = 1;
        if (listColumnsCnt == 1) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(act);
            recyclerView.setLayoutManager(linearLayoutManager);
        } else {
            gridLayoutManager = new GridLayoutManager(act, listColumnsCnt,
                    GridLayoutManager.VERTICAL, false);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {

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

                    if (positionType == dataAdapter.TYPE_HEADER) {
                        return gridLayoutManager.getSpanCount();
                    } else {
                        return dataAdapter.getItemViewType(position) == 1 ? 1 :
                                (valueCount % listColumnsCnt == 1 ? gridLayoutManager.getSpanCount() : 1);
                    }
                }
            });
            recyclerView.setLayoutManager(gridLayoutManager);
        }
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
                R.drawable.color_line_01));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        recyclerView.setAdapter(scaleAdapter);

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

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

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

    @Override
    public void onClick(View view) {

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

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

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());

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

                    resultPutRuleStatus(result);
                }
            });
            String homegrpRuleId = util.null2string(alTotalList.get(selectPosition)
                    .get(Constants.KEY_HOMEGRP_RULE_ID));
            String useYn = util.null2string(alTotalList.get(selectPosition).get(Constants.KEY_USE_YN));
            String statusCode = "";

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

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

        try {
            if (result.getStatusCode() == 200) {
                onListReload();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if (errorCode.equals("401")) {
                    customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                } else {
                    customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
    }

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

        try {
            HttpSend httpSend;

            if (searchType.equals("D")) {
                httpSend = new HttpSend(act, false);
            } else {
                httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());
            }

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

                    resultGetRules(result);
                }
            });
            httpSend.G_rules(ruleId, searchType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

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

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

                util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(activeCount);
                util.getTextView(toolbar, R.id.tvToolbarTitle4).setText(inactiveCount);

                ArrayList<HashMap<String, Object>> alList = util.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 = util.null2string(hmTemp.get(Constants.KEY_RULE_ID));
                        if (minRuleId.equals("")) {
                            minRuleId = ruleId;
                        } else if (util.str2long(minRuleId) > util.str2long(ruleId)) {
                            minRuleId = ruleId;
                        }
                        if (util.str2long(maxRuleId) < util.str2long(ruleId)) {
                            maxRuleId = ruleId;
                        }
                        alTotalList.add(hmTemp);
                    }

                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    hmTemp.put(Constants.KEY_MORE_YN, "N");
                    alTotalList.add(hmTemp);
                } else {
                    if (searchType.equals("D")) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp.put(Constants.KEY_MORE_YN, "N");
                        alTotalList.add(hmTemp);
                    }
                }
                loading = false;
                setHomeHubStateAll();
                swipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if (errorCode.equals("401")) {
                    customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                } else {
                    customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
    }

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

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());

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

                    resultDeleteRule(result);
                }
            });
            String homegrpRuleId = util.null2string(alTotalList.get(selectPosition)
                    .get(Constants.KEY_HOMEGRP_RULE_ID));
            httpSend.D_rules_homegrp_rule_id(homegrpRuleId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (result.getStatusCode() == 200) {
                isReload = true;
                alTotalList.remove(selectPosition);
                dataAdapter.notifyDataSetChanged();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if (errorCode.equals("401")) {
                    customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                } else {
                    customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
                } else {
                    act.onBackPressed();
                }
                break;
            case Constants.MSG810:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_D_RULES_HOMEGRP_RULE_ID), 10);
                }
                break;
            case Constants.MSG818:
                if (btnResult == 1) {
                    String homegrpRuleId = util.null2string(alTotalList.get(selectPosition)
                            .get(Constants.KEY_HOMEGRP_RULE_ID));
                    Intent intent = new Intent(act, RulesEdit.class);
                    intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                    intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, homegrpRuleId);
                    util.callActivityForResult(act, intent, Constants.ACT_RULES_EDIT);
                }
                break;
            default:
                break;
        }
    }

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

        try {
            dialogListBuilder = new DialogCustomList.Builder(act);
            dialogListBuilder.setList(list);
            dialogListBuilder.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:
                            util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            util.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            dataAdapter.setListCheck(true);
                            dataAdapter.notifyDataSetChanged();
                            setRefresh(false);
                            break;
                        default:
                            break;
                    }
                }
            });
            dialogListBuilder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

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

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

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

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

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == act.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() {

        loading = true;
        searchType = "";
        ruleId = "";
        if (setHomeHubStateList()) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES), 10);
        }
    }

    @Override
    public void onLogout() {
    }

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

        if (callType == 0) {
            util.callBtnGoogleAnalytics(activityName, "Create_Rules", "");
            //추가하기
            goRulesEdit();
        } else if (callType == 1) {
            util.callBtnGoogleAnalytics(activityName, "ViewDetail_Rules", "");
            // 상세보기
            String homegrpRuleId = util.null2string(alTotalList.get(position).get(Constants.KEY_HOMEGRP_RULE_ID));
            Intent intent = new Intent(act, RulesDetail.class);
            intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, homegrpRuleId);
            util.callActivityForResult(act, intent, Constants.ACT_RULES_DETAIL);
        } else if (callType == 2) {
            util.callBtnGoogleAnalytics(activityName, "Delete_Rules", "");
            selectPosition = position;
            customDialog.msgAlert(act, Constants.MSG810, R.string.MSG_TITLE_003,
                    util.getString(act, R.string.layout_delete), util.getString(act, R.string.layout_cancel));
        } else if (callType == 3) {
            util.callBtnGoogleAnalytics(activityName, "Active_Rules", "");
            // 활성화 비활성화
            selectPosition = position;
            String useYn = util.null2string(alTotalList.get(position).get(Constants.KEY_USE_YN));
            if (useYn.equals("Y")) {
                util.setVibrator(100);
                util.setShowToast(act, util.getString(act, R.string.MSG808), Toast.LENGTH_SHORT);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(
                        MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), 10);
            } else if (useYn.equals("N")) {
                util.setVibrator(100);
                util.setShowToast(act, util.getString(act, R.string.MSG809), Toast.LENGTH_SHORT);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(
                        MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), 10);
            } else if (useYn.equals("X")) {
                customDialog.msgAlert(act, Constants.MSG818, R.string.MSG_TITLE_000,
                        util.getString(act, R.string.MSG_BTN_EDIT),
                        util.getString(act, 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_HOMEGRP_RULE_ID_STATUS:
                    //dialog_show();
                    sendPutRuleStatus();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
