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

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

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import org.json.JSONObject;

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

public class Main_More extends CustomActivity implements View.OnClickListener,
                                                         CustomDialog.OnMsgAlterToResult {

    /**
     * Called when the activity is first created.
     */

    private AppConfig appConfig;
    private Util         util         = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private Intent   intent;
    private Activity act;
    private              String                             sDateTime                       = "";
    private              String                             sMaxDatetime                    = "";
    private              String                             sMinDatetime                    = "";
    private              boolean                            bMore                           = false;
    private              String                             sSearchPlan                     = "";
    private              ArrayList<HashMap<String, Object>> alTotalList                     = new ArrayList<HashMap<String, Object>>();
    private              int                                iType                           = 0;
    private static final int                                MSG_COM_G_DASHBOARD             = 1;
    private static final int                                MSG_COM_P_HOMEGRP_PROFILE_IMAGE = 3;

    private View vClickView = null;
    private int          iLastPosition;
    private RecyclerView rcvList;
    private LinearLayout llFooter1, llFooter2;
    private        View    vFooter;
    private        View    header;
    private static WebView wvWebView;
    private        Dialog  dialog;
    private String  sModeId     = "";
    private String  sMenu       = "";
    private Boolean bFirst      = true;
    private Boolean bSend       = false;
    private String  sSelectMode = "";
    private String  sFileName   = "";
    ArrayList<HashMap<String, Object>> alList_Mode_list = new ArrayList<HashMap<String, Object>>();
    private Bitmap mImage;
    private boolean loading = false;
    private SwipeRefreshLayout swipeRefreshLayout;

    private int illWidth;
    private int illHeight;
    private int iIvPosition = 0;
    private ViewPager vpMain;
    private final static int                                VideoSizeChanged           = -1;
    private              ArrayList<HashMap<String, Object>> alDeviceInfo               = new ArrayList<HashMap<String, Object>>();
    private              ArrayList<HashMap<String, Object>> alList_HomeMonitering_list = new ArrayList<HashMap<String, Object>>();

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

        act = Main_More.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        View viewToLoad = LayoutInflater.from(act).inflate(R.layout.main_more, null);
        this.setContentView(viewToLoad);

        if ( savedInstanceState != null ) {

        } else {
            Intent intent = getIntent();
            //            sCallType = util.null2string(intent.getStringExtra(Constants.EXTRA_CALL_TYPE));
        }

        displayListView();
    }

    private void displayListView() {

        //        if ( appConfig.getSelect_Homegrp_Grade_Code().equals("MAS") ) {
        //            util.getView(act, R.id.rlHomeImage).setOnClickListener(this);
        //            util.getView(act, R.id.ivHomeIconSet).setVisibility(View.VISIBLE);
        //        } else {
        //            util.getView(act, R.id.ivHomeIconSet).setVisibility(View.INVISIBLE);
        //        }
        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);
    }

    private void setRefresh(boolean bVal) {

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

    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 v) {

        switch (v.getId()) {
            case R.id.btnReload:
                v.setEnabled(false);
                ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
                break;
            //            case R.id.rlHomeImage:
            //                intent = new Intent(act, Image_Select.class);
            //                intent.putExtra(Constants.EXTRA_CROP_TYPE, true);
            //                util.callActivityForResultNoAnim(act, intent, Constants.ACT_IMAGE_SELECT);
            //                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, Message_Center.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:
                onBackPressed();
                break;
            default:
                break;
        }
    }

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            if ( !appConfig.getLogin() ) {
                return true;
            }
            switch (msg.what) {
                case MSG_COM_G_DASHBOARD:
                    send_G_dashboard();
                    break;
                case MSG_COM_P_HOMEGRP_PROFILE_IMAGE:
                    send_P_homegrp_profile_image();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private void send_P_homegrp_profile_image() {

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

                    result_P_homegrp_profile_image(result);
                }
            });

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

    private void result_P_homegrp_profile_image(Response rpResult) {

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

                //회원 번호
                sFileName = util.null2string(joResult.get(Constants.HTTP_image_file_name));
                //                util.setRefreshImage(act, sFileName, R.id.ivHomeIcon);
            } 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);
        }
        bSend = false;
    }

    private void send_G_dashboard() {

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

                    result_G_dashboard(result);
                }
            });

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

    private void result_G_dashboard(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                //                HashMap<String, Object> hmResult = util.jsonToMap(rpResult.getContent());
                String sHTTP_notice_count = util.null2string(joResult.get(Constants.HTTP_notice_count));
                String sHTTP_push_count = util.null2string(joResult.get(Constants.HTTP_push_count));
                if (sHTTP_notice_count.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(sHTTP_notice_count);
                }
                if (sHTTP_push_count.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(sHTTP_push_count);
                }

                String sHTTP_homegrp_id = util.null2string(joResult.get(Constants.HTTP_homegrp_id));
                String sHTTP_homegrp_name = "";
                if ( joResult.has(Constants.HTTP_homegrp_name) ) {
                    sHTTP_homegrp_name = util.null2string(joResult.get(Constants.HTTP_homegrp_name));
                }
                String sHTTP_image_file_name = "";
                if ( joResult.has(Constants.HTTP_image_file_name) ) {
                    sHTTP_image_file_name = util.null2string(joResult.get(Constants.HTTP_image_file_name));
                }
                String sHTTP_mode_list = "";
                if ( joResult.has(Constants.HTTP_mode_list) ) {
                    sHTTP_mode_list = util.null2string(joResult.get(Constants.HTTP_mode_list));
                }

                //                util.getTextView(act, R.id.tvHomeName).setText(sHTTP_homegrp_name);
                //                util.setRefreshImage(act, sHTTP_image_file_name, util.getImageView(act, R.id.ivHomeIcon));
                if ( appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("") ) {
                    util.getView(act, R.id.llHomeGateway).setEnabled(false);
                } else {
                    util.getView(act, R.id.llHomeGateway).setEnabled(true);
                }
                alList_Mode_list = util.jsonToArrayListMap(sHTTP_mode_list);
                if ( alList_Mode_list.size() > 0 ) {
                    for ( int iRow = 0; iRow < alList_Mode_list.size(); iRow++ ) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp = alList_Mode_list.get(iRow);

                        String sTempHTTP_mode_id = util.null2string(hmTemp.get(Constants.HTTP_mode_id));
                        String sTempHTTP_basic_mode_code = util.null2string(hmTemp.get(Constants.HTTP_basic_mode_code));
                        String sTempHTTP_mode_name = util.null2string(hmTemp.get(Constants.HTTP_mode_name));
                        String sTempHTTP_use_yn = util.null2string(hmTemp.get(Constants.HTTP_use_yn));
                        final String sTempHTTP_image_file_name = util.null2string(hmTemp.get(Constants.HTTP_image_file_name));
                        final String sTempHTTP_image_file_active_name = util.null2string(hmTemp.get(Constants.HTTP_image_file_active_name));
                        final String sTempHTTP_image_file_disable_name = util.null2string(hmTemp.get(Constants.HTTP_image_file_disable_name));

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

                        tvTempImageView.setText(sTempHTTP_mode_name);
                        if ( appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("") ) {
                            vView.setEnabled(false);
                            util.setRefreshImage(act, sTempHTTP_image_file_disable_name, ivTempImageView);
                        } else {
                            vView.setEnabled(true);
                            if ( sTempHTTP_use_yn.equals("Y") ) {
                                vView.setSelected(true);
                                util.setRefreshImage(act, sTempHTTP_image_file_active_name, ivTempImageView);
                                sSelectMode = sTempHTTP_mode_id;
                            } else {
                                vView.setSelected(false);
                                util.setRefreshImage(act, sTempHTTP_image_file_name, ivTempImageView);
                            }

                            vView.setTag(iRow);
                            vView.setOnClickListener(new View.OnClickListener() {
                                int iTag = 0;

                                @Override public void onClick(View v) {

                                    iTag = (int) v.getTag();
                                    if ( appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON") ) {
                                        String sTempHTTP_mode_id = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_mode_id));
                                        String sTempHTTP_basic_mode_code = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_basic_mode_code));
                                        String sTempHTTP_mode_name = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_mode_name));
                                        String sTempHTTP_use_yn = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_use_yn));
                                        String sTempHTTP_image_file_view_name = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_image_file_view_name));
                                        String sTempHTTP_image_file_active_name = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_image_file_active_name));
                                        String sTempHTTP_homegrp_scene_id = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_homegrp_rule_id));
                                        String sTempHTTP_delete_cnt = util.null2string(alList_Mode_list.get(iTag).get(Constants.HTTP_delete_cnt));

                                        intent = new Intent(act, Homemode.class);
                                        intent.putExtra(Constants.EXTRA_MODE_ID, sTempHTTP_mode_id);
                                        intent.putExtra(Constants.EXTRA_BASIC_MODE_CODE, sTempHTTP_basic_mode_code);
                                        intent.putExtra(Constants.EXTRA_MODE_ICON, sTempHTTP_image_file_view_name);
                                        intent.putExtra(Constants.EXTRA_MODE_ICON1, sTempHTTP_image_file_active_name);
                                        intent.putExtra(Constants.EXTRA_MODE_NAME, sTempHTTP_mode_name);
                                        intent.putExtra(Constants.EXTRA_HOMEGRP_RULE_ID, sTempHTTP_homegrp_scene_id);
                                        intent.putExtra(Constants.EXTRA_MODE_DEL_YN, sTempHTTP_delete_cnt);
                                        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(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);
        }
        try {
            util.getView(act, R.id.btnReload).setEnabled(true);
        } catch (Exception ex) {

        }
    }

    @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;
            default:
                break;
        }
    }
    @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_HOMEMODE:
                case Constants.ACT_HOMEHUB:
                    if ( data == null ) {
                        return;
                    }
                    Boolean bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
                    }
                    break;
                case Constants.ACT_SETTING:
                    break;
                case Constants.ACT_IMAGE_SELECT:
                    sFileName = util.null2string(data.getStringExtra(Constants.EXTRA_IMAGE_FILE_NAME));

                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_HOMEGRP_PROFILE_IMAGE), 10);

                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEMODE:
                    if ( data == null ) {
                        return;
                    }
                    Boolean bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        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;
                //                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                //                    if ( bReload_Flag ) {
                //                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_GROUPS_DEVICES), 10);
                //                    }
                //                    break;
            }
            // if (appConfig.getGoErr()) {
            // act.setResult(act.RESULT_CANCELED, new Intent());
            // finish();
            // }
        }
    }
}
