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

package com.ntels.kneet.v3.view.rules;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
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 android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.List_Interface;
import com.ntels.kneet.v3.common.c_interface.Main_Interface;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.util.recyclerview.DividerItemDecoration;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.dialog.Dialog_Custom_List;

import org.json.JSONObject;

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

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

public class Fragment_Rules extends Fragment implements View.OnClickListener,
                                                        CustomDialog.OnMsgAlterToResult,
                                                        List_Interface {

    /*툴바 관련*/
    private Toolbar toolbar;

    /*통신 관련*/
    private              ArrayList<HashMap<String, Object>> alTotalList                            = new ArrayList<HashMap<String, Object>>();
    private              int                                iType                                  = 0;
    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;

    /*리스트 관련*/
    private Fragment_Rules_Adapter     dataAdapter;
    private RecyclerView               rcvList;
    private SwipeRefreshLayout         swipeRefreshLayout;
    private GridLayoutManager          glmList;
    private LinearLayoutManager        llmList;
    private Dialog_Custom_List.Builder dialog_list_builder;
    private boolean loading            = false;
    private boolean bListHeader        = false;
    private boolean bListFooter        = false;
    private boolean bListFooterVisible = false;
    private boolean bListFooterAnd     = false;
    private int     iListColumnsCnt    = 1;

    /*공통*/
    private Activity       act;
    private AppConfig      appConfig;
    private Main_Interface mCallback;
    private Intent         intent;
    private Util         util            = new Util();
    private CustomDialog customDialog    = new CustomDialog();
    private String       sCallType       = "";
    private Boolean      bPollingPause   = false;
    private Boolean      bPollingCancel  = false;
    private Boolean      bActStop        = false;
    private String       sSearch_Type    = "";
    private String       sRule_id        = "";
    private String       sMaxRule_id     = "";
    private String       sMinRule_id     = "";
    private boolean      bMore           = true;
    private int          iSelectPosition = -1;
    Boolean bReload_Flag = false;
    private String       sActName                 = "";

    //    @Override public void onAttach(Context context) {
    //
    //        super.onAttach(context);
    //
    //        Activity activity;
    //
    //        if ( context instanceof Activity ) {
    //            activity = (Activity) context;
    //            try {
    //                mCallback = (Main_Interface) activity;
    //            } catch (ClassCastException e) {
    //                throw new ClassCastException(activity.toString() + " must implement Main_Interface");
    //            }
    //        }
    //    }

    @Override public void onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            mCallback = (Main_Interface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement Main_Interface");
        }
    }
    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @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();
        sActName = "Rules_List";
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

//        Tracker t = appConfig.getTracker(AppConfig.TrackerName.APP_TRACKER);
//        t.setScreenName(act.getClass().getSimpleName());
//        t.send(new HitBuilders.AppViewBuilder().build());
        util.callActGoogleAnalytics(sActName);
        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 v) {

                util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                util.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                dataAdapter.setListCheck(false);
                setRefresh(true);
                if ( bReload_Flag ) {
                    onListReload();
                } else {
                    dataAdapter.notifyDataSetChanged();
                }
                //                setHomeHubStateTitle();
            }
        });
        util.getView(toolbar, R.id.btnToolbarMore).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {

                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.getSelect_Homegrp_Id().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 ( dialog_list_builder != null ) {
                dialog_list_builder.create().dismiss();
            }
        } else {
            //홈그룹 있을경우
            if ( appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("") ) {
                //홈그룹은 있고 홈허브가 없는경우
                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 ( dialog_list_builder != null ) {
                    dialog_list_builder.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));
                    //                    util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                } else {
                    //홈그룹은 있고 홈허브가 온라인인 경우
                    util.getView(toolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
                    util.getView(toolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
                }
            }
        }
    }

    public boolean setHomeHubStateList() {

        //        Dlog.v("Things setHomeHubStateList()");
        Boolean bListLoad = 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.getSelect_Homegrp_Id().equals("") ) {
            //홈그룹 없을경우
                util.getView(act, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
            dataAdapter.setListCheck(false);
            dataAdapter.notifyDataSetChanged();
            setRefresh(false);
        } else {
            //홈그룹 있을경우
            if ( appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("") ) {
                //홈그룹은 있고 홈허브가 없는경우
                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();
                bListLoad = true;
            }
        }
        return bListLoad;
    }

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

        bListFooter = true;
        bListFooterVisible = true;
        dataAdapter = new Fragment_Rules_Adapter(act, R.layout.row_rules_list, R.layout.row_rules_list, R.layout.row_footer_rules_list, alTotalList, this);
        dataAdapter.setFooterCheck(bListFooter);
        dataAdapter.setFooterVisible(bListFooterVisible);

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

                    int iPositionType = dataAdapter.getItemViewType(position);
                    int iTotalConut = dataAdapter.getItemCount();
                    int iValueConut = dataAdapter.getItemCount();
                    if ( bListHeader ) {
                        iValueConut = iTotalConut - 1;
                    }

                    if ( iPositionType == dataAdapter.TYPE_HEADER ) {
                        return glmList.getSpanCount();
                    } else {
                        return dataAdapter.getItemViewType(position) == 1 ? 1 : (iValueConut % iListColumnsCnt == 1 ? glmList.getSpanCount() : 1);
                    }
                }
            });
            rcvList.setLayoutManager(glmList);
        }
        rcvList.addItemDecoration(new DividerItemDecoration(getActivity(), R.drawable.list_color_line_01));
        //        rcvList.setItemAnimator(new FadeInAnimator());
        //        rcvList.setAdapter(dataAdapter);
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        rcvList.setAdapter(scaleAdapter);

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

    private void setRefresh(boolean bVal) {

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

    @Override public void onClick(View v) {

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

    Handler ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_RULES:
                    //dialog_show();
                    send_G_rules();
                    break;
                case MSG_COM_D_RULES_HOMEGRP_RULE_ID:
                    //dialog_show();
                    send_D_rules_homegrp_rule_id();
                    break;
                case MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS:
                    //dialog_show();
                    send_P_rules_homegrp_rule_id_status();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_P_rules_homegrp_rule_id_status
     * 2. ClassName :
     * 3. Comment   : [Send][POST]홈 규칙 상태 변경(해당 규칙의 상태를 변경한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_P_rules_homegrp_rule_id_status() {

        try {
            HttpSend httpSend;

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

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

                    result_P_rules_homegrp_rule_id_status(result);
                }
            });
            String sHTTP_homegrp_rule_id = util.null2string(alTotalList.get(iSelectPosition).get(Constants.HTTP_homegrp_rule_id));
            String sHTTP_use_yn = util.null2string(alTotalList.get(iSelectPosition).get(Constants.HTTP_use_yn));
            String sHTTP_status_code = "";

            if ( sHTTP_use_yn.equals("Y") ) {
                sHTTP_status_code = "03";
            } else if ( sHTTP_use_yn.equals("N") ) {
                sHTTP_status_code = "02";
            }
            httpSend.P_rules_homegrp_rule_id_status(sHTTP_homegrp_rule_id, sHTTP_status_code);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_P_rules_homegrp_rule_id_status
     * 2. ClassName :
     * 3. Comment   : [Result][POST]홈 규칙 상태 변경(해당 규칙의 상태를 변경한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_P_rules_homegrp_rule_id_status(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                onListReload();
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

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

    /**
     * <PRE>
     * 1. MethodName: send_G_rules
     * 2. ClassName :
     * 3. Comment   : [Send][GET]홈 규칙 목록 조회(홈의 규칙 목록을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_G_rules() {

        try {
            HttpSend httpSend;

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

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

                    result_G_rules(result);
                }
            });
            httpSend.G_rules(sRule_id, sSearch_Type);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_G_rules
     * 2. ClassName :
     * 3. Comment   : [Result][GET]홈 규칙 목록 조회(홈의 규칙 목록을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_G_rules(Response rpResult) {

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

                String sHTTP_active_count = util.null2string(joResult.get(Constants.HTTP_active_count));
                String sHTTP_inactive_count = util.null2string(joResult.get(Constants.HTTP_inactive_count));
                String sHTTP_rules = util.null2string(joResult.get(Constants.HTTP_rules));

                util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(sHTTP_active_count);
                util.getTextView(toolbar, R.id.tvToolbarTitle4).setText(sHTTP_inactive_count);

                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(sHTTP_rules);
                if ( alList.size() > 0 ) {
                    bMore = true;
                    for ( int iRow = 0; iRow < alList.size(); iRow++ ) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp = alList.get(iRow);
                        String sHTTP_rule_id = util.null2string(hmTemp.get(Constants.HTTP_rule_id));
                        if ( sMinRule_id.equals("") ) {
                            sMinRule_id = sHTTP_rule_id;
                        } else if ( util.str2long(sMinRule_id) > util.str2long(sHTTP_rule_id) ) {
                            sMinRule_id = sHTTP_rule_id;
                        }
                        if ( util.str2long(sMaxRule_id) < util.str2long(sHTTP_rule_id) ) {
                            sMaxRule_id = sHTTP_rule_id;
                        }
                        alTotalList.add(hmTemp);
                    }

                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    hmTemp.put(Constants.HTTP_MORE_YN, "N");
                    alTotalList.add(hmTemp);
                } else {
                    bMore = false;
                    if ( sSearch_Type.equals("D") ) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp.put(Constants.HTTP_MORE_YN, "N");
                        alTotalList.add(hmTemp);
                    }
                }
                loading = false;
                setHomeHubStateAll();
                swipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }
    /**
     * <PRE>
     * 1. MethodName: send_D_rules_homegrp_rule_id
     * 2. ClassName :
     * 3. Comment   : [Send][DELETE]홈 규칙 삭제(해당 규칙을 삭제한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_D_rules_homegrp_rule_id() {

        try {
            HttpSend httpSend;

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

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

                    result_D_rules_homegrp_rule_id(result);
                }
            });
            String sHTTP_homegrp_rule_id = util.null2string(alTotalList.get(iSelectPosition).get(Constants.HTTP_homegrp_rule_id));
            httpSend.D_rules_homegrp_rule_id(sHTTP_homegrp_rule_id);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_D_rules_homegrp_rule_id
     * 2. ClassName :
     * 3. Comment   : [Result][DELETE]홈 규칙 삭제(해당 규칙을 삭제한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_D_rules_homegrp_rule_id(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                //                JSONObject joResult = new JSONObject(rpResult.getContent());
                //                String sHTTP_homegrp_member_list = util.null2string(joResult.get(Constants.HTTP_homegrp_member_list));
                //                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(sHTTP_homegrp_member_list);
                bReload_Flag = true;
                alTotalList.remove(iSelectPosition);
                dataAdapter.notifyDataSetChanged();
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

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

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {

            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                } else {
                    act.onBackPressed();
                }
                break;
            case Constants.MSG810:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_D_RULES_HOMEGRP_RULE_ID), 10);
                }
                break;
            case Constants.MSG818:
                if ( iBtnResult == 1 ) {
                    String sHTTP_homegrp_rule_id = util.null2string(alTotalList.get(iSelectPosition).get(Constants.HTTP_homegrp_rule_id));
                    Intent intent = new Intent(act, Rules_Edit.class);
                    intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                    intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, sHTTP_homegrp_rule_id);
                    util.callActivityForResult(act, intent, Constants.ACT_RULES_EDIT);
                }
                break;
            default:
                break;
        }
    }

    private void MsgAlertList(ArrayList<HashMap<String, Object>> alList) {

        try {
            dialog_list_builder = new Dialog_Custom_List.Builder(act);
            dialog_list_builder.setList(alList);
            dialog_list_builder.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:
                            Rules_Edit();
                            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;
                    }
                }
            });
            dialog_list_builder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

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

    public void Rules_Edit() {

        Intent intent = new Intent(act, Rules_Edit.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;
                    }
                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_RULES_EDIT:
                    if ( data == null ) {
                        return;
                    }
                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        onListReload();
                    }
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_RULES_DETAIL:
                    if ( data == null ) {
                        return;
                    }
                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_RULES_EDIT:
                    if ( data == null ) {
                        return;
                    }
                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        onListReload();
                    }
                    break;
            }
            // if (appConfig.getGoErr()) {
            // act.setResult(act.RESULT_CANCELED, new Intent());
            // finish();
            // }
        }
    }

    @Override public void onListReload() {

        loading = true;
        bMore = true;
        sSearch_Type = "";
        sRule_id = "";
        if ( setHomeHubStateList() ) {
            ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_RULES), 10);
        }
    }

    @Override public void onLogout() {
        //        mCallback.onLogout();
    }
    @Override public void onCallAction(int iCallType, int iPosition) {

        if ( iCallType == 0 ) {
            util.callBtnGoogleAnalytics(sActName, "Create_Rules", "");
            //추가하기
            Rules_Edit();
        } else if ( iCallType == 1 ) {
            util.callBtnGoogleAnalytics(sActName, "ViewDetail_Rules", "");
            // 상세보기
            String sHTTP_homegrp_rule_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_homegrp_rule_id));
            Intent intent = new Intent(act, Rules_Detail.class);
            intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, sHTTP_homegrp_rule_id);
            util.callActivityForResult(act, intent, Constants.ACT_RULES_DETAIL);
        } else if ( iCallType == 2 ) {
            util.callBtnGoogleAnalytics(sActName, "Delete_Rules", "");
            // 삭제하기
            //            String sHTTP_group_name = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_group_name));
            //            String sHTTP_device_name = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_device_name));
            //            String sCOMPANY_DESC = util.getString(act, R.string.layout_things_device_add_07);
            iSelectPosition = iPosition;
            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 ( iCallType == 3 ) {
            util.callBtnGoogleAnalytics(sActName, "Active_Rules", "");
            // 활성화 비활성화
            iSelectPosition = iPosition;
            String sHTTP_use_yn = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_use_yn));
            if ( sHTTP_use_yn.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 ( sHTTP_use_yn.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 ( sHTTP_use_yn.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));
            }
        }
    }
}
