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

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

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.db.DatabaseOpenHelper;
import com.ntels.onecable.admin.common.db.SqlManager;
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.common.websocket.WebSocketService;
import com.ntels.onecable.admin.view.dialog.CustomDialog;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
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.text.Editable;
import android.text.TextWatcher;
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 butterknife.ButterKnife;
import butterknife.OnClick;

import static com.ntels.onecable.admin.common.Constants.EXTRA_ERROR_CODE;

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

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

    private static final int MSG_COM_P_MEMBER_PASSWORD_TEMP = 1;
    ArrayList<HashMap<String, Object>> mModeList = new ArrayList<>();
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private AppConfig mAppConfig;
    private SqlManager mSqlManager = new SqlManager();
    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 mCtrtGrpId = "";
    private String mCustId = "";
    private Boolean mIsAutoLogin = false;
    private int mCustIdPosition = 0;
    private ArrayList<String> mCustIdMemberList = new ArrayList<String>();
    private ArrayList<String> mCustIdValueList = new ArrayList<String>();
    private ArrayList<String> mCustIdDispList = new ArrayList<String>();
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<>();
    //    @BindView(R.id.ivMsoLogo) ImageView mMsoLogo;
    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {

            String search = mUtil.getEditText(mActivity, R.id.edtSearch).getText().toString();

            if (mUtil.null2string(search).length() > 0) {
                mUtil.getView(mActivity, R.id.btnSearch).setEnabled(true);
            } else {
                mUtil.getView(mActivity, R.id.btnSearch).setEnabled(false);
            }
        }
    };

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(Constants.EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                Dlog.i(TAG, "websocket message mType : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if (jsonObject.has(Constants.KEY_RESULT_CODE)) {
                    resultCode = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_CODE));
                }
                if (jsonObject.has(Constants.KEY_RESULT_MSG)) {
                    resultMsg = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_MSG));
                }
//                if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_COMMAND)) {
//                    resultWsNodeCommand(jsonObject);
//                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_COMMAND_RESULT)) {
//                    notificationWsNodeCommandResult(jsonObject);
//                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_CONTENT)) {
//                    notificationWsNodeContent(jsonObject);
//                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_REGISTER_RESULT)) {
//                    notificationWsNodeRegisterResult(jsonObject);
//                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODES_RELOAD)) {
//                    resultWsNodeReload(jsonObject);
//                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_DELETE_RESULT)) {
//                    notificationWsNodeDelete(jsonObject);
//                } else {
//                    /*final String finalResultMsg = resultMsg;
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
//                        }
//                    });*/
//                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {
//            if (!mUtil.getTopActivityName(mActivity).equals("view.Main")) {
//                return;
//            }
            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {
                case Constants.WEBSOCKET_ERROR_TIMEOUT:
                    Dlog.i(TAG, "WEBSOCKET_ERROR_TIMEOUT!!!");
//                    for (HashMap<String, Object> hm : mAlTotalList) {
//                        hm.put(Constants.KEY_REQUEST_TIME, "");
//                    }
                    break;
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    Dlog.i(TAG, "WEBSOCKET_ERROR_NOT_CONNECTED!!!");
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                    break;
                default:
                    break;
            }
//            setHomeHubStateList();
        }
    }

    @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.fragment_admin, container, false);
        ButterKnife.bind(this, rootView);

        return rootView;
    }

    @Override
    public void onStop() {

        super.onStop();
        Dlog.v("onStop()");
    }

    @Override
    public void onStart() {

        super.onStart();
        Dlog.v("onStart()");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

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

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

        mUtil.callActGoogleAnalytics(actName);

        displayListView();
    }


    /**
     * UI display.
     */
    private void displayListView() {
        if(mAppConfig.getIsCustomerConn()){
            mUtil.getView(mActivity, R.id.btnTempPassSend).setEnabled(true);
            mUtil.getView(mActivity, R.id.btnHubSetting).setEnabled(true);
            mUtil.getTextView(mActivity, R.id.tvTempSendMsg).setText(mUtil.getString(mActivity, R.string.layout_admin_04));
        } else {
            mUtil.getView(mActivity, R.id.btnTempPassSend).setEnabled(false);
            mUtil.getView(mActivity, R.id.btnHubSetting).setEnabled(false);
            mUtil.getTextView(mActivity, R.id.tvTempSendMsg).setText(mUtil.getString(mActivity, R.string.layout_admin_03));
        }

        mIsAutoLogin = mAppConfig.getIsAutoLogin();
        Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
        if (mIsAutoLogin) {
            mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(true);
        } else {
            mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(false);
        }

        mUtil.getView(mActivity, R.id.btnLogout).setEnabled(true);
        mUtil.getTextView(mActivity, R.id.tvLoginId).setText(mUtil.getString(mActivity, R.string.layout_admin_09, mAppConfig.getLoginId()));
        mUtil.getTextView(mActivity, R.id.tvAppVersion).setText(mUtil.getString(mActivity, R.string.layout_admin_09, mUtil.getVersionName(mActivity)));


    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @OnClick({R.id.btnTempPassSend, R.id.btnHubSetting, R.id.btnLogout, R.id.llAutoLogin})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btnTempPassSend: {
                mUtil.getView(mActivity, R.id.btnTempPassSend).setEnabled(false);
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_MEMBER_PASSWORD_TEMP), Constants.HANDLER_DELAY_MILLIS);

                break;
            }
            case R.id.btnHubSetting: {
                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//                if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
////                    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
//                }
                if (null == bluetoothAdapter) {
                    // TODO: 2017-05-17 혹시 블루투스 지원을 안하면?
                } else {
                    if (!bluetoothAdapter.isEnabled()) {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG930);
                        return;
                    } else {
                        Intent intent = new Intent(mActivity, HomehubBleStep1.class);
                        mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOMEHUB_BLE_STEP1);
                    }
                }
                break;
            }
            case R.id.llAutoLogin: {
                if (view.isSelected()) {
                    view.setSelected(false);
                } else {
                    view.setSelected(true);
                }
                mIsAutoLogin = view.isSelected();
                mAppConfig.setIsAutoLogin(mIsAutoLogin);
                //db 입력작업
                SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
                String sql = "";
                sql = "";
                sql = mSqlManager.qryUpdateLoginInfoAutoLogin(mIsAutoLogin);
                db.execSQL(sql);
                db.close();
                break;
            }
            case R.id.btnLogout: {
                mCustomDialog.msgAlert(mActivity, Constants.MSG805);
                break;
            }
            default:
                break;
        }
    }


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

        switch (msgId) {
            case Constants.MSG805:
                if (btnResult == 1) {
                    mAppConfig.setLogout(true);
                    mUtil.callApp_Start(mActivity, "LOGOUT");
                }
                break;
            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);
                }
                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) {
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                default:
                    break;
            }
        }
    }

    /**
     * [REST][POST] 임시비밀번호 재발송 요청.
     *
     */
    private void sendPostMemberPasswordTemp() {
        try {
            HttpSend httpSend;
            httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPostMemberPasswordTemp(result);
                }
            });

            httpSend.postMemberPasswordTemp(mAppConfig.getCustId(), mAppConfig.getCustomerMemberId(), mAppConfig.getCustomerPhone());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 비밀번호 찾기 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostMemberPasswordTemp(Response result) {

        mUtil.getView(mActivity, R.id.btnTempPassSend).setEnabled(true);
        try {
            if (result.getStatusCode() == 200) {
                mCustomDialog.msgAlert(mActivity, Constants.MSG938);
            } else {
                JSONObject joResult = new JSONObject(result.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));

                mUtil.setShowToast(mActivity, resultMsg, Toast.LENGTH_SHORT);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    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_MEMBER_PASSWORD_TEMP:
                    sendPostMemberPasswordTemp();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
