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

package com.ntels.onecable.view.homemember;

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

/**
 * <pre>
 * 1. ClassName :   FragmentHomeMember
 * 2. FileName  :   FragmentHomeMember.java
 * 3. Package   :   com.ntels.onecable.view.homemember
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class FragmentHomeMember extends Fragment implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult,
        ListInterface {

    private static final int MSG_COM_G_HOMEGRP_MEMBERS = 1;
    private static final int MSG_COM_D_HOMEGRP_MEMBERS = 2;

    /**
     * 멤버 타입 코드
     */
    public static final String HOMEGRP_MEMBER = "01";
    public static final String INVITATION_MEMBER = "02";

    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 FragmentHomeMemberAdapter dataAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private GridLayoutManager gridLayoutManager;
    private DialogCustomList.Builder dialogListBuilder;
    private boolean loading = false;
    private boolean isListHeader = false;
    private boolean isListFooter = 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 int mLimitCount = 10;

    @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 View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Dlog.v("onCreateView()");
        View rootView = inflater.inflate(R.layout.fragment_homemember, container, false);

        return rootView;
    }

    @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 onActivityCreated(Bundle savedInstanceState) {

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

        act = getActivity();
        String actName = "HomeMember_List";
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        util.callActGoogleAnalytics(actName);
        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_join));
        util.getTextView(toolbar, R.id.tvToolbarTitle2).setText("");
        util.getTextView(toolbar, R.id.tvToolbarTitle3).setText(util.getString(act, R.string.layout_wait));
        util.getTextView(toolbar, R.id.tvToolbarTitle4).setText("");

//        util.getView(toolbar, R.id.btnToolbarDel).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                view.setEnabled(false);
//                Boolean isCheck = false;
//                for (int row = 0; row < alTotalList.size(); row++) {
//                    if (alTotalList.get(row).get(Constants.KEY_CHECK_YN).equals("Y")) {
//                        isCheck = true;
//                        break;
//                    }
//                }
//                if (isCheck) {
//                    loading = true;
//                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_D_HOMEGRP_MEMBERS), 10);
//                } else {
//                    util.setShowToast(act, util.getString(act, R.string.MSG814), Toast.LENGTH_SHORT);
//                    view.setEnabled(true);
//                }
//            }
//        });
        util.getView(toolbar, R.id.btnToolbarClose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                util.getTextView(toolbar, R.id.btnToolbarDel).setVisibility(View.GONE);
                util.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                util.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
//                for (int row = 0; row < alTotalList.size(); row++) {
//                    alTotalList.get(row).put(Constants.KEY_CHECK_YN, "N");
//                }

                dataAdapter.setListCheck(false);
                dataAdapter.setPermissionCheck(false);
                dataAdapter.setDelCheck(false);
                dataAdapter.notifyDataSetChanged();
                setRefresh(true);
            }
        });
        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>>();
                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    if (alTotalList.size() > 2) {
                        alMenuList.add(util.getPopMenu(21));
                    }
                    alMenuList.add(util.getPopMenu(15));
                    if (alTotalList.size() > 2) {
                        alMenuList.add(util.getPopMenu(16));
                    }
                } else {
                    alMenuList.add(util.getPopMenu(17));
                }
                alMenuList.add(util.getPopMenu(6));
                msgAlertList(alMenuList);
            }
        });
    }

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

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

        isListFooter = true;
        dataAdapter = new FragmentHomeMemberAdapter(act, R.layout.row_homemember_list,
                R.layout.row_homemember_list, R.layout.row_footer_homemember_list,
                alTotalList, this);
        dataAdapter.setFooterCheck(isListFooter);

        RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.rcvList);
        recyclerView.setHasFixedSize(true);
        listColumnsCnt = 2;
        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 == FragmentHomeMemberAdapter.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.list_color_line_01));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        recyclerView.setAdapter(scaleAdapter);

        setHomeHubStateTitle();
        onListReload();
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 타이틀과 리스트를 보여준다.
     */
    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);
                }
                // 리스트가 2개 이하일경우에는 본인이 마스터인경우와 푸터랑 해서 2Row이기 때문에 삭제 상태를 다시 일반상태로 변환함
                if (alTotalList.size() <= 2) {
                    util.getTextView(toolbar, R.id.btnToolbarDel).setVisibility(View.GONE);
                    util.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                    util.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 다른 리스트를 보여준다.
     *
     * @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 (false/*appConfig.getCtrtGroupId().equals("")*/) {
            //홈그룹 없을경우
            util.getView(act, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
            dataAdapter.setListCheck(false);
            dataAdapter.setPermissionCheck(false);
            dataAdapter.setDelCheck(false);
            dataAdapter.notifyDataSetChanged();
            setRefresh(false);
        } else {
            //홈그룹 있을경우
            if (false/*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.setPermissionCheck(false);
                    dataAdapter.setDelCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                } else {
                    util.getView(act, R.id.llNoHub_Guest).setVisibility(View.VISIBLE);
                    dataAdapter.setListCheck(false);
                    dataAdapter.setPermissionCheck(false);
                    dataAdapter.setDelCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                }
            } else {
                //                if ( alTotalList.size() > 0 ) {
                swipeRefreshLayout.setVisibility(View.VISIBLE);
                // 리스트가 2개 이하일경우에는 본인이 마스터인경우와 푸터랑 해서 2Row이기 때문에 삭제 상태를 다시 일반상태로 변환함
                if (alTotalList.size() <= 2) {
                    dataAdapter.setListCheck(false);
                    dataAdapter.setPermissionCheck(false);
                    dataAdapter.setDelCheck(false);
                    setRefresh(true);
                }
                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    dataAdapter.setFooterVisible(true);
                } else {
                    dataAdapter.setFooterVisible(false);
                }
                dataAdapter.notifyDataSetChanged();
                isListLoad = true;
            }
        }
        return isListLoad;
    }

    /**
     * {@link #swipeRefreshLayout} enable/disable.
     *
     * @param isEnable true or false
     */
    private void setRefresh(boolean isEnable) {

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

    /**
     * {@link HomeMemberAdd} 로 이동.
     */
    public void homeMemberAdd() {

        Intent intent = new Intent(act, HomeMemberAdd.class);
        util.callActivityForResult(act, intent, Constants.ACT_HOMEMEMBER_ADD);
    }

    @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:
                homeMemberAdd();
                break;
            default:
                break;
        }
    }

    /**
     * 홈그룹 멤버 강퇴/초대 취소(홈그룹으로 초대받은 멤버의 정보를 변경한다) 요청.
     */
    private void sendDeleteHomegrpMembers() {

        try {
            HttpSend httpSend;
            httpSend = new HttpSend(act);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultDeleteHomegrpMembers(result);
                }
            });

            String temp = "";
            String temp1 = "";
            for (int row = 0; row < alTotalList.size(); row++) {
                Dlog.v("alTotalList.get(row).get(Constants.KEY_CHECK_YN) = "
                        + alTotalList.get(row).get(Constants.KEY_CHECK_YN));
                if (alTotalList.get(row).get(Constants.KEY_CHECK_YN).equals("Y")) {
                    if (alTotalList.get(row).get(Constants.KEY_MEMBER_TYPE_CODE).equals("01")) {
                        temp += (temp.equals("") ? "" : ",")
                                + alTotalList.get(row).get(Constants.KEY_MEMBER_ID);
                    } else {
                        temp1 += (temp1.equals("") ? "" : ",")
                                + alTotalList.get(row).get(Constants.KEY_NICKNAME);
                    }
                }
            }

            httpSend.deleteHomegrpMembers(temp, temp1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        loading = false;
        try {
            if (response.getStatusCode() == 200) {
                util.setShowToast(act, util.getString(act, R.string.MSG880), Toast.LENGTH_SHORT);

                onListReload();
            } else {
                JSONObject joResult = new JSONObject(response.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));

                switch (errorCode) {
                    case "401":
                        customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                        break;
                    case "401-106":
                        customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                        break;
                    default:
                        util.setShowToast(act, errorMsg, Toast.LENGTH_SHORT);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
//        try {
//            util.getView(toolbar, R.id.btnToolbarDel).setEnabled(true);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
    }

    /**
     * 홈그룹 멤버 목록 조회(홈그룹의 멤버 목록을 조회한다) 요청.
     */
    private void sendGetHomegrpMembers() {

        try {
            HttpSend httpSend;

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

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

                    resultGetHomegrpMembers(result);
                }
            });
            alTotalList.clear();
            swipeRefreshLayout.setVisibility(View.GONE);
            httpSend.getHomeGroupMembers();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        loading = false;
        try {
            if (response.getStatusCode() == 200) {

                JSONObject joResult = new JSONObject(response.getContent());
                mLimitCount = util.null2int(joResult.get(Constants.KEY_LIMIT_CNT));
                String homegrpMemberList = util.null2string(
                        joResult.get(Constants.KEY_CTRT_GRP_MEMBER_LIST));
                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(homegrpMemberList);
                int memberCnt = 0;
                int invitationCnt = 0;
                if (alList.size() > 0) {
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> tempMap;
                        tempMap = alList.get(row);

                        String memberTypeCode = util.null2string(tempMap.get(Constants.KEY_MEMBER_TYPE_CODE));
                        tempMap.put(Constants.KEY_CHECK_YN, "N");
                        alTotalList.add(tempMap);

                        if (HOMEGRP_MEMBER.equals(memberTypeCode)) {
                            memberCnt++;
                        } else if (INVITATION_MEMBER.equals(memberTypeCode)) {
                            invitationCnt++;
                        }
                    }

                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    hmTemp.put(Constants.KEY_CHECK_YN, "N");
                    alTotalList.add(hmTemp);
                }
                util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(String.valueOf(memberCnt));
                util.getTextView(toolbar, R.id.tvToolbarTitle4).setText(String.valueOf(invitationCnt));

                setHomeHubStateAll();
                swipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.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));

                switch (errorCode) {
                    case "401":
                        customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                        break;
                    case "401-106":
                        customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                        break;
                    default:
                        customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                        break;
                }
            }
        } 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.MSG996:
                if (btnResult == 1) {
                    loading = true;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_D_HOMEGRP_MEMBERS), 10);
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
                }
                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) {

                    Dlog.v("which = " + which);
                    dialog.dismiss();
                    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:
                            break;
                        case 12:
                            break;
                        case 15:
                            Intent intent = new Intent(act, HomeMemberAdd.class);
                            util.callActivityForResult(act, intent, Constants.ACT_HOMEMEMBER_ADD);
                            break;
                        case 16:
                            //삭제
//                            util.getTextView(toolbar, R.id.btnToolbarDel).setVisibility(View.VISIBLE);
                            util.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            util.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            for (int row = 0; row < alTotalList.size(); row++) {
                                alTotalList.get(row).put(Constants.KEY_CHECK_YN, "N");
                            }

                            dataAdapter.setDelCheck(true);
                            dataAdapter.notifyDataSetChanged();
                            setRefresh(false);

                            break;
                        case 17:
                            callback.onHomeMemberWidthdraw();
                            break;
                        case 21:
                            //권한양도
//                            util.getTextView(toolbar, R.id.btnToolbarDel).setVisibility(View.VISIBLE);
                            util.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            util.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            for (int row = 0; row < alTotalList.size(); row++) {
                                alTotalList.get(row).put(Constants.KEY_CHECK_YN, "N");
                            }

                            dataAdapter.setPermissionCheck(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();
        }
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        Boolean isReload = false;
        Dlog.v("jino1111");
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_HOMEMEMBER_DETAIL:
                case Constants.ACT_HOMEMEMBER_ADD:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEMEMBER_DETAIL:
                case Constants.ACT_HOMEMEMBER_ADD:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onListReload() {

        loading = true;

        if (setHomeHubStateList()) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS), 10);
        }
        // do something
    }

    @Override
    public void onLogout() {
    }

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

        if (callType == 0) {
            //추가하기
            homeMemberAdd();
        } else if (callType == 1) {
            // 상세보기
        } else if (callType == 2) {
            // 삭제하기
            alTotalList.get(position).put(Constants.KEY_CHECK_YN, "Y");
            String member = "";
            if ("".equals(alTotalList.get(position).get(Constants.KEY_NICKNAME))) {
                member = alTotalList.get(position).get(Constants.KEY_MEMBER_ID).toString();
            } else {
                member = alTotalList.get(position).get(Constants.KEY_NICKNAME).toString();
            }
            String msg = getString(R.string.MSG877, member);
            customDialog.msgAlert(act, Constants.MSG996, msg, R.string.MSG_TITLE_004);
//            dataAdapter.notifyDataSetChanged();
//            loading = true;
//            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_D_HOMEGRP_MEMBERS), 10);
        } else if (callType == 3) {
            // 권한 양도
            // 여기서 권한 양도 API 호출후 화면 갱신 그리고 전체 권한 변경 로직 들어가야함
            alTotalList.get(position).put(Constants.KEY_CHECK_YN, "Y");
            String member = "";
            if ("".equals(alTotalList.get(position).get(Constants.KEY_NICKNAME))) {
                member = alTotalList.get(position).get(Constants.KEY_MEMBER_ID).toString();
            } else {
                member = alTotalList.get(position).get(Constants.KEY_NICKNAME).toString();
            }
            String msg = getString(R.string.MSG878, member);
            customDialog.msgAlert(act, Constants.MSG995, msg, R.string.MSG_TITLE_005);
//            notifyDataSetChanged();

        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_G_HOMEGRP_MEMBERS:
                    sendGetHomegrpMembers();
                    break;
                case MSG_COM_D_HOMEGRP_MEMBERS:
                    sendDeleteHomegrpMembers();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
