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

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

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

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

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

    private static final String TAG = FragmentMainMore.class.getSimpleName();

    private static final int MSG_COM_P_DASHBOARD = 1;
    private static final int MSG_COM_P_MODE_CHANGE = 2;
    private static final int MSG_COM_P_HOMEGRP_PROFILE_IMAGE = 3;
    ArrayList<HashMap<String, Object>> mModeList = new ArrayList<>();
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private Intent mIntent;
    private Activity mActivity;
    private int mType = 0;
    private boolean loading = false;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private MainInterface mCallback;
    private String mModeCode = "";
    private String mModeId = "";
    @BindView(R.id.ivMsoLogo) ImageView mMsoLogo;


    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

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

    @Override
    public void onCreate(Bundle savedInstanceState) {

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

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

        Dlog.v("onCreateView()");
        View rootView = inflater.inflate(R.layout.main_more, container, false);
        ButterKnife.bind(this, rootView);

        return rootView;
    }

    @Override
    public void onStop() {

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

    @Override
    public void onStart() {

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

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

        mActivity = getActivity();
        String actName = "MainMore";
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        mUtil.callActGoogleAnalytics(actName);

        displayListView();
    }


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

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

                if (!loading) {
                    loading = true;
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DASHBOARD), Constants.HANDLER_DELAY_MILLIS);
                }
            }
        });
//        setHomeHubState();
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DASHBOARD), Constants.HANDLER_DELAY_MILLIS);
    }

    /**
     * 홈허브 Off시 아이콘 표시.
     */
    /*private void setHomeHubState() {

        if (mAppConfig.getSelectCtrtGroupHomehubOnlineState().equals("OFF")) {
            mUtil.getView(mActivity, R.id.ivHomeGatewayState).setVisibility(View.VISIBLE);
        } else {
            mUtil.getView(mActivity, R.id.ivHomeGatewayState).setVisibility(View.GONE);
        }
    }*/

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @OnClick({R.id.llNotice, R.id.llFaq, R.id.llMessageCenter, R.id.llHomehub, R.id.llSetting})
    public void onClick(View view) {

        switch (view.getId()) {
            /*case R.id.btnReload:
                view.setEnabled(false);
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DASHBOARD), Constants.HANDLER_DELAY_MILLIS);
                break;*/
            case R.id.llNotice:
                mIntent = new Intent(mActivity, Notice.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_NOTICE);
                break;
//            case R.id.llMessageCenter:
//                mIntent = new Intent(mActivity, MessageCenter.class);
//                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_MESSAGE_CENTER);
//                break;
            case R.id.llHomehub:
                mIntent = new Intent(mActivity, HomehubList.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_HOMEHUB_LIST);
                break;
            case R.id.llSetting:
                mIntent = new Intent(mActivity, Setting.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_SETTING);
                break;
            /*case R.id.ivClose:
                mActivity.onBackPressed();
                break;*/
            default:
                break;
        }
    }

    /**
     * 홈그룹 이미지 변경(홈그룹의 프로필 이미지를 수정) 요청.
     *//*
    private void sendPostHomegrpProfileImage() {

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

                    resultPostHomegrpProfileImage(result);
                }
            });

            //공통 변수 입력
            httpSend.P_homegrp_profile_image(Constants.KEY_IMAGE_FILE, fileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());

                //회원 번호
                fileName = mUtil.null2string(joResult.get(Constants.KEY_PROFILE_IMAGE));
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

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

    /**
     * 홈모드 변경(현재 홈모드를 변경한다) 요청.
     */
    private void sendPutModeChange() {

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

                    resultPutModeChange(result);
                }
            });

            //공통 변수 입력
            httpSend.putMode(mModeCode, mModeId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
//                JSONObject joResult = new JSONObject(response.getContent());
//                Dlog.v(joResult.toString());

                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DASHBOARD), Constants.HANDLER_DELAY_MILLIS);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

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

    /**
     * 대시보드 정보 조회(홈그룹 모드 조회, 공지, 알림 갯수 조회 등) 요청.
     */
    private void sendPostDashboard() {

        try {
            HttpSend httpSend = new HttpSend(mActivity, !mSwipeRefreshLayout.isRefreshing());
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPostDashboard(result);
                }
            });

            Dlog.v("mUtil.getPreferences(mActivity, \"notice_read_datetime\")",
                    mUtil.getPreferences(mActivity, Constants.KEY_NOTICE_READ_DATETIME));
            //공통 변수 입력
            httpSend.postDashboard(mUtil.getPreferences(mActivity, Constants.KEY_NOTICE_READ_DATETIME),
                    mUtil.getPreferences(mActivity, Constants.KEY_MESSAGE_READ_DATETIME));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(response.getContent());
                String noticeCount = mUtil.null2string(joResult.get(Constants.KEY_NOTICE_COUNT));
                String pushCount = mUtil.null2string(joResult.get(Constants.KEY_PUSH_COUNT));
                String deviceEventYn = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_EVENT_YN));
                String phoneAuthYn = mUtil.null2string(joResult.get(Constants.KEY_PHONE_AUTH_YN));
                String msoImageUrl = mUtil.null2string(joResult.get(Constants.KEY_MSO_IMAGE_URL));

                if (!"".equals(msoImageUrl)) {
                    mUtil.setRefreshImage(mActivity, msoImageUrl, mMsoLogo);
                }
                if (noticeCount.equals("0")) {
                    mUtil.getTextView(mActivity, R.id.tvNoticeCnt).setVisibility(View.GONE);
                } else {
                    mUtil.getTextView(mActivity, R.id.tvNoticeCnt).setVisibility(View.VISIBLE);
                    mUtil.getTextView(mActivity, R.id.tvNoticeCnt).setText(noticeCount);
                }
                if (pushCount.equals("0")) {
                    mUtil.getTextView(mActivity, R.id.tvMessageCenterCnt).setVisibility(View.GONE);
                } else {
                    mUtil.getTextView(mActivity, R.id.tvMessageCenterCnt).setVisibility(View.VISIBLE);
                    mUtil.getTextView(mActivity, R.id.tvMessageCenterCnt).setText(pushCount);
                }
                if (deviceEventYn.equals("Y")) {
                    mUtil.getView(mActivity, R.id.ivHomehubIcon).setVisibility(View.VISIBLE);
                } else {
                    mUtil.getView(mActivity, R.id.ivHomehubIcon).setVisibility(View.GONE);
                }
                if (phoneAuthYn.equals("Y")) {
                    mUtil.getView(mActivity, R.id.ivSettingIcon).setVisibility(View.GONE);
                } else {
                    mUtil.getView(mActivity, R.id.ivSettingIcon).setVisibility(View.VISIBLE);
                }

                String modeList = "";
                if (joResult.has(Constants.KEY_MODE_LIST)) {
                    modeList = mUtil.null2string(joResult.get(Constants.KEY_MODE_LIST));
                }

                if (!mAppConfig.getIsCtrtGroupHomehub()) {
                    mUtil.getView(mActivity, R.id.llHomehub).setEnabled(false);
                } else {
                    mUtil.getView(mActivity, R.id.llHomehub).setEnabled(true);
                }
                this.mModeList = mUtil.jsonToArrayListMap(modeList);
                if (this.mModeList.size() > 0) {
                    for (int row = 0; row < this.mModeList.size(); row++) {
                        HashMap<String, Object> tempMap;
                        tempMap = this.mModeList.get(row);

                        String modeId = mUtil.null2string(tempMap.get(Constants.KEY_MODE_ID));
                        String modeName = mUtil.null2string(tempMap.get(Constants.KEY_MODE_NAME));
                        String useYn = mUtil.null2string(tempMap.get(Constants.KEY_USE_YN));
                        /*final String tempImageFileName = mUtil.null2string(
                                tempMap.get(Constants.KEY_PROFILE_IMAGE));
                        final String tempImageFileActiveName = mUtil.null2string(
                                tempMap.get(Constants.KEY_IMAGE_FILE_ACTIVE_NAME));
                        final String tempImageFileDisableName = mUtil.null2string(
                                tempMap.get(Constants.KEY_IMAGE_FILE_DISABLE_NAME));*/

                        View view = mUtil.getView(mActivity, mUtil.getIDvalues(mActivity, "llHomeMode" + (row + 1)));
                        TextView tvTempImageView = mUtil.getTextView(mActivity, mUtil.getIDvalues(mActivity, "tvHomeModeIcon" + (row + 1)));
//                        final ImageView ivTempImageView = mUtil.getImageView(mActivity, mUtil.getIDvalues(mActivity, "ivHomeModeIcon" + (row + 1)));

                        tvTempImageView.setText(modeName);
                        if (!mAppConfig.getIsCtrtGroupHomehub()) {
                            view.setEnabled(false);
//                            mUtil.setImage(mActivity, tempImageFileDisableName, ivTempImageView);
                        } else {
                            view.setEnabled(true);
                            if (useYn.equals("Y")) {
                                view.setSelected(true);
//                                mUtil.setImage(mActivity, tempImageFileActiveName, ivTempImageView);
                            } else {
                                view.setSelected(false);
//                                mUtil.setImage(mActivity, tempImageFileName, ivTempImageView);
                            }

                            view.setTag(row);
                            view.setOnClickListener(new View.OnClickListener() {
                                int tag = 0;

                                @Override
                                public void onClick(View view) {

                                    tag = (int) view.getTag();
                                    if (mAppConfig.getSelectCtrtGroupHomehubOnlineState().equals("ON")) {

                                        mModeCode = mUtil.null2string(mModeList.get(tag).get(Constants.KEY_BASIC_MODE_CODE));
                                        mModeId = mUtil.null2string(mModeList.get(tag).get(Constants.KEY_MODE_ID));

                                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_MODE_CHANGE),
                                                Constants.HANDLER_DELAY_MILLIS);

                                        /*mIntent = new Intent(mActivity, Homemode.class);

                                        String tempModeId = mUtil.null2string(
                                                FragmentMainMore.this.mModeList.get(tag).get(Constants.KEY_MODE_ID));
                                        mIntent.putExtra(Constants.EXTRA_MODE_ID, tempModeId);
                                        String tempBasicModeCode = mUtil.null2string(
                                                FragmentMainMore.this.mModeList.get(tag).get(Constants.KEY_BASIC_MODE_CODE));
                                        LogUtil.i(TAG, "EXTRA_BASIC_MODE_CODE : " + tempBasicModeCode);
                                        mIntent.putExtra(Constants.EXTRA_BASIC_MODE_CODE, tempBasicModeCode);
                                        String tempImageFileViewName = mUtil.null2string(
                                                FragmentMainMore.this.mModeList.get(tag).get(Constants.KEY_IMAGE_FILE_VIEW_NAME));
                                        mIntent.putExtra(Constants.EXTRA_MODE_ICON, tempImageFileViewName);
                                        String tempImageFileActiveName = mUtil.null2string(
                                                FragmentMainMore.this.mModeList.get(tag).get(Constants.KEY_IMAGE_FILE_ACTIVE_NAME));
                                        mIntent.putExtra(Constants.EXTRA_MODE_ICON1, tempImageFileActiveName);
                                        String tempModeName = mUtil.null2string(
                                                FragmentMainMore.this.mModeList.get(tag).get(Constants.KEY_MODE_NAME));
                                        mIntent.putExtra(Constants.EXTRA_MODE_NAME, tempModeName);
                                        String tempHomegrpSceneId = mUtil.null2string(
                                                FragmentMainMore.this.mModeList.get(tag).get(Constants.KEY_HOMEGRP_RULE_ID));
                                        mIntent.putExtra(Constants.EXTRA_HOMEGRP_RULE_ID, tempHomegrpSceneId);
                                        String tempDeleteCnt = mUtil.null2string(
                                                FragmentMainMore.this.mModeList.get(tag).get(Constants.KEY_DELETE_CNT));
                                        mIntent.putExtra(Constants.EXTRA_MODE_DEL_YN, tempDeleteCnt);
                                        mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_HOMEMODE);*/
                                    } else {
                                        mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG866),
                                                Toast.LENGTH_SHORT);
                                        return;
                                    }
                                }
                            });
                        }
                    }
                }

                loading = false;
                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        /*try {
            mUtil.getView(mActivity, R.id.btnReload).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }*/
    }

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

        switch (msgId) {

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

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

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_HOMEMODE:
                case Constants.ACT_HOMEHUB_LIST:
                    if (data == null) {
                        return;
                    }
                    Boolean isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DASHBOARD), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                case Constants.ACT_SETTING:
                    break;
                /*case Constants.ACT_IMAGE_SELECT:
                    fileName = mUtil.null2string(data.getStringExtra(Constants.EXTRA_IMAGE_FILE_NAME));

                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                            MSG_COM_P_HOMEGRP_PROFILE_IMAGE), 10);
                    break;*/
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEMODE:
                    if (data == null) {
                        return;
                    }
                    Boolean isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DASHBOARD), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                case Constants.ACT_NOTICE:
                case Constants.ACT_MESSAGE_CENTER:
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DASHBOARD), Constants.HANDLER_DELAY_MILLIS);
                    break;
                default:
                    break;
            }
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            if (!mAppConfig.getIsLogin()) {
                return true;
            }
            switch (msg.what) {
                case MSG_COM_P_DASHBOARD:
                    sendPostDashboard();
                    break;
                case MSG_COM_P_MODE_CHANGE:
                    sendPutModeChange();
                    break;
                /*case MSG_COM_P_HOMEGRP_PROFILE_IMAGE:
                    sendPostHomegrpProfileImage();
                    break;*/
                default:
                    break;
            }
            return true;
        }
    }
}
