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

package com.ntels.onecable.view.mainmore;

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.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.LogUtil;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.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;

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

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

    private static final int MSG_COM_G_DASHBOARD = 1;
    private static final int MSG_COM_P_HOMEGRP_PROFILE_IMAGE = 3;
    ArrayList<HashMap<String, Object>> modeList = new ArrayList<>();
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private AppConfig appConfig;
    private Util util = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private Intent intent;
    private Activity act;
    private int type = 0;
    private String fileName = "";
    private boolean loading = false;
    private SwipeRefreshLayout swipeRefreshLayout;
    private MainInterface callback;


    @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.main_more, 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 = "MainMore";
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        util.callActGoogleAnalytics(actName);

        displayListView();
    }


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

        util.getView(act, R.id.llNotice).setOnClickListener(this);
        util.getView(act, R.id.llMessagecenter).setOnClickListener(this);
        util.getView(act, R.id.llHomeGateway).setOnClickListener(this);
        util.getView(act, R.id.llSetting).setOnClickListener(this);
        util.getView(act, R.id.llHomeMode1).setOnClickListener(this);
        util.getView(act, R.id.llHomeMode2).setOnClickListener(this);
        util.getView(act, R.id.llHomeMode3).setOnClickListener(this);
        util.getView(act, R.id.llHomeMode4).setOnClickListener(this);
        util.getView(act, R.id.ivClose).setOnClickListener(this);
        util.getView(act, R.id.btnReload).setOnClickListener(this);
        util.getTextView(act, R.id.tvNoticeCnt).setVisibility(View.GONE);
        util.getTextView(act, R.id.tvMessagecenterCnt).setVisibility(View.GONE);

        swipeRefreshLayout = (SwipeRefreshLayout) act.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 (!loading) {
                    loading = true;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
                }
            }
        });
        setHomeHubState();
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
    }

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

        if (appConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
            util.getView(act, R.id.ivHomeGatewayState).setVisibility(View.VISIBLE);
        } else {
            util.getView(act, R.id.ivHomeGatewayState).setVisibility(View.GONE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btnReload:
                view.setEnabled(false);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
                break;
            case R.id.llNotice:
                intent = new Intent(act, Notice.class);
                util.callActivityForResult(act, intent, Constants.ACT_NOTICE);
                break;
            case R.id.llMessagecenter:
                intent = new Intent(act, MessageCenter.class);
                util.callActivityForResult(act, intent, Constants.ACT_MESSAGE_CENTER);
                break;
            case R.id.llHomeGateway:
                intent = new Intent(act, Homehub.class);
                util.callActivityForResult(act, intent, Constants.ACT_HOMEHUB);
                break;
            case R.id.llSetting:
                intent = new Intent(act, Setting.class);
                util.callActivityForResult(act, intent, Constants.ACT_SETTING);
                break;
            case R.id.llHomeMode1:
                break;
            case R.id.llHomeMode2:
                break;
            case R.id.llHomeMode3:
                break;
            case R.id.llHomeMode4:
                break;
            case R.id.ivClose:
                act.onBackPressed();
                break;
            default:
                break;
        }
    }

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

        try {
            HttpSend httpSend = new HttpSend(act);
            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 = util.null2string(joResult.get(Constants.KEY_IMAGE_FILE_NAME));
            } 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));

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

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

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

                    resultGetDashboard(result);
                }
            });

            Dlog.v("util.getPreferences(mActivity, \"notice_read_datetime\")",
                    util.getPreferences(act, "notice_read_datetime"));
            //공통 변수 입력
            httpSend.G_dashboard(util.getPreferences(act, "notice_read_datetime"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(response.getContent());
                String noticeCount = util.null2string(joResult.get(Constants.KEY_NOTICE_COUNT));
                String pushCount = util.null2string(joResult.get(Constants.KEY_PUSH_COUNT));
                if (noticeCount.equals("0")) {
                    util.getTextView(act, R.id.tvNoticeCnt).setVisibility(View.GONE);
                } else {
                    util.getTextView(act, R.id.tvNoticeCnt).setVisibility(View.VISIBLE);
                    util.getTextView(act, R.id.tvNoticeCnt).setText(noticeCount);
                }
                if (pushCount.equals("0")) {
                    util.getTextView(act, R.id.tvMessagecenterCnt).setVisibility(View.GONE);
                } else {
                    util.getTextView(act, R.id.tvMessagecenterCnt).setVisibility(View.VISIBLE);
                    util.getTextView(act, R.id.tvMessagecenterCnt).setText(pushCount);
                }

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

                if (!appConfig.getIsHomegrpHomehub()){
                    util.getView(act, R.id.llHomeGateway).setEnabled(false);
                } else {
                    util.getView(act, R.id.llHomeGateway).setEnabled(true);
                }
                this.modeList = util.jsonToArrayListMap(modeList);
                if (this.modeList.size() > 0) {
                    for (int row = 0; row < this.modeList.size(); row++) {
                        HashMap<String, Object> tempMap;
                        tempMap = this.modeList.get(row);

                        String modeId = util.null2string(tempMap.get(Constants.KEY_MODE_ID));
                        String modeName = util.null2string(tempMap.get(Constants.KEY_MODE_NAME));
                        String useYn = util.null2string(tempMap.get(Constants.KEY_USE_YN));
                        final String tempImageFileName = util.null2string(
                                tempMap.get(Constants.KEY_IMAGE_FILE_NAME));
                        final String tempImageFileActiveName = util.null2string(
                                tempMap.get(Constants.KEY_IMAGE_FILE_ACTIVE_NAME));
                        final String tempImageFileDisableName = util.null2string(
                                tempMap.get(Constants.KEY_IMAGE_FILE_DISABLE_NAME));

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

                        tvTempImageView.setText(modeName);
                        if (!appConfig.getIsHomegrpHomehub()){
                            view.setEnabled(false);
                            util.setImage(act, tempImageFileDisableName, ivTempImageView);
                        } else {
                            view.setEnabled(true);
                            if (useYn.equals("Y")) {
                                view.setSelected(true);
                                util.setImage(act, tempImageFileActiveName, ivTempImageView);
                            } else {
                                view.setSelected(false);
                                util.setImage(act, tempImageFileName, ivTempImageView);
                            }

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

                                @Override
                                public void onClick(View view) {

                                    tag = (int) view.getTag();
                                    if (appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON")) {

                                        intent = new Intent(act, Homemode.class);

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

                loading = false;
                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));

                if (errorCode.equals("401")) {
                    customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                } else {
                    customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
        try {
            util.getView(act, R.id.btnReload).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        switch (msgId) {

            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
//                } else {
//                    act.onBackPressed();
                }
                break;
            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:
                    if (data == null) {
                        return;
                    }
                    Boolean isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
                    }
                    break;
                case Constants.ACT_SETTING:
                    break;
                case Constants.ACT_IMAGE_SELECT:
                    fileName = util.null2string(data.getStringExtra(Constants.EXTRA_IMAGE_FILE_NAME));

                    comHandler.sendMessageDelayed(comHandler.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) {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
                    }
                    break;
                case Constants.ACT_NOTICE:
                case Constants.ACT_MESSAGE_CENTER:
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
                    break;
                default:
                    break;
            }
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            if (!appConfig.getLogin()) {
                return true;
            }
            switch (msg.what) {
                case MSG_COM_G_DASHBOARD:
                    sendGetDashboard();
                    break;
                case MSG_COM_P_HOMEGRP_PROFILE_IMAGE:
                    sendPostHomegrpProfileImage();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
