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

import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.ble.BluetoothLeService;
import com.ntels.onecable.admin.common.ble.GattAttributeResolver;
import com.ntels.onecable.admin.common.mdns.MdnsDiscovery;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

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

/**
 * <pre>
 * 1. ClassName :   HomehubRegister
 * 2. FileName  :   HomehubRegister.java
 * 3. Package   :   com.ntels.onecable.view.things
 * 4. Date      :   2016-11-24
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class HomehubBleStep3 extends CustomActivity implements View.OnClickListener
        , CustomDialog.OnMsgAlterToResult {

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

    private static final int MSG_COM_BLE_GET_CONNECT = 1;
    private static final int MSG_COM_BLE_GET_SSID = 2;
    //    private static final int MSG_COM_BLE_SCAN = 3;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 99999999;
    private static final int CONNECT_MAX_TIME_SEC = 10;
    private static final long SCAN_PERIOD = CONNECT_MAX_TIME_SEC * 1000;
    int mType;
    ArrayList<HashMap<String, Object>> mAlTotalList = new ArrayList<>();
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private Activity mActivity;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private MdnsDiscovery mMdnsDiscovery;
    private MdnsDiscovery.onDiscoveryListener mOnDiscoveryListener;
    private boolean mIsBleConnect = false;
    private boolean mIsDestroy = false;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Intent mIntent;
    private Handler mHandler = new Handler();
    private BluetoothLeService mBluetoothLeService;
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            Dlog.v("jino = onServiceConnected");
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }

            Log.v("jino", "asdfasdfasdfas");
            // Automatically connects to the device upon successful start-up initialization.
//            mBluetoothLeService.connect(mDeviceAddress);

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new
            ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    private boolean mConnected = false;
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                Log.v("jino", "connected");
                mConnected = true;
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                Log.v("jino", "disconnected");
                mConnected = false;
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                Dlog.v("jino ACTION_GATT_SERVICES_DISCOVERED");
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        filter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_UUID);
        filter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        filter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return filter;
    }

    private void displayData(String result) {

        if (result != null) {
            Log.v("jino getdata", result);

            HashMap<String, Object> hmTemp = new HashMap<>();
            hmTemp = mUtil.jsonToMap(result);
            String uuid = mUtil.null2string(hmTemp.get(Constants.KEY_UUID));
            String data = mUtil.null2string(hmTemp.get(Constants.KEY_DATA));
            if (uuid.equals(GattAttributeResolver.CONNECTION_CHR_UUID)) {
                if (data.equals("0")) {
                    // disconnect
                    mIsBleConnect = false;
                    mUtil.getTextView(mActivity, R.id.tvMsg).setText(mUtil.getString(mActivity, R.string.layout_homehub_ble_step3_04));
                } else  if (data.equals("1")){
                    // connect
                    mIsBleConnect = true;
                    mUtil.getTextView(mActivity, R.id.tvMsg).setText(mUtil.getString(mActivity, R.string.layout_homehub_ble_step3_02));
                } else if (data.equals("2")){
                    // 연결중
                    mIsBleConnect = false;
                    mUtil.getTextView(mActivity, R.id.tvMsg).setText(mUtil.getString(mActivity, R.string.layout_homehub_ble_step3_04));
                }
                dialog_dismiss();
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_GET_SSID), Constants.HANDLER_DELAY_MILLIS);
            } else if (uuid.equals(GattAttributeResolver.SSID_CHR_UUID)) {
                if (mIsBleConnect) {
                    mUtil.getTextView(mActivity, R.id.tvSsid).setText(mUtil.getString(mActivity, R.string.layout_homehub_ble_step3_05, data));
                } else if (!data.equals("")){
                    mUtil.getTextView(mActivity, R.id.tvSsid).setText(mUtil.getString(mActivity, R.string.layout_homehub_ble_step3_05, data));
                }  else {
                    mUtil.getTextView(mActivity, R.id.tvMsg).setText(mUtil.getString(mActivity, R.string.layout_homehub_ble_step3_03));
                }
            }
//            mDataField.setText(data);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        mActivity = HomehubBleStep3.this;
        mCustomDialog.setOnMsgAlterToResultEvent(this);

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

//        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
//        mBluetoothAdapter = bluetoothManager.getAdapter();

        final Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

        setToolbar();
        viewInit();
        Dlog.v("jinoasdfasdfasdfasdfasdfasdfasdfasd");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            CheckPermission();
        } else {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_GET_CONNECT), Constants.HANDLER_DELAY_MILLIS);
        }

    }

    @TargetApi(Build.VERSION_CODES.M)
    public void CheckPermission() {
        if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs location access");
            builder.setMessage("Please grant location access so this app can detect peripherals.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                }
            });
            builder.show();
        } else {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_GET_CONNECT), Constants.HANDLER_DELAY_MILLIS);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    System.out.println("coarse location permission granted");
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_GET_CONNECT), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in" +
                            " the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }
                return;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        mIntent = new Intent();
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_THINGS_HOMEHUB_SET_PASSWORD:
                case Constants.ACT_THINGS_HOMEHUB_ASSIGN_PASSWORD:
                    mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);
                    finish();
                    break;
                case Constants.ACT_HOMEHUB_BLE_STEP4:
                    Boolean isRetry = data.getBooleanExtra(Constants.EXTRA_RETRAY_FLAG, false);
                    if (isRetry) {
//                        startLoading();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEHUB_BLE_STEP4:
                    Boolean isFlowEnd = data.getBooleanExtra(Constants.EXTRA_FLOW_END_FLAG, false);
                    Boolean isEnd = data.getBooleanExtra(Constants.EXTRA_END_FLAG, false);
//                    Boolean isTimeout = data.getBooleanExtra(Constants.EXTRA_TIMEOUT_FLAG, false);
                    if (isFlowEnd) {
                        mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.VISIBLE);
                    } else if (isEnd) {
                        mActivity.setResult(RESULT_CANCELED, data);
                        finish();
                    } else {

                    }
                    break;
                case Constants.ACT_THINGS_HOMEHUB_ASSIGN_PASSWORD:
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        onBackPressedEnd();
        return;
    }

    private void onBackPressedRetry(){
        mIntent = new Intent();
        mIntent.putExtra(Constants.EXTRA_RETRAY_FLAG, true);
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }


    private void onBackPressedFlowEnd(){
        mIntent = new Intent();
        mIntent.putExtra(Constants.EXTRA_FLOW_END_FLAG, true);
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }

    private void onBackPressedEnd(){
        mIntent = new Intent();
        mIntent.putExtra(Constants.EXTRA_END_FLAG, true);
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
//        if (mBluetoothLeService != null) {
//            final boolean result = mBluetoothLeService.connect1(mDeviceAddress);
//            Log.d(TAG, "Connect request result=" + result);
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Dlog.v("onDestroy()");
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llBtn1:
                mIntent = new Intent(mActivity, HomehubBleStep4.class);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOMEHUB_BLE_STEP4);
                break;
            case R.id.llBtn2:
                mCustomDialog.msgAlert(mActivity, Constants.MSG905);
                break;
            default:
                break;
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {
        switch (msgId) {
            case Constants.MSG905:
                if (btnResult == 1) {
                    onBackPressedEnd();
                }
                break;
            default:
                break;
        }
    }

    /**
     * view initialize.
     */
    private void viewInit() {
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {
        Toolbar toolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, toolbar);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setText(mUtil.getString(mActivity, R.string.layout_homehub_ble_step2_01));
    }

    public void SendBleOP(int iVal) {
        BluetoothGattCharacteristic getBleGattC = null;
        if (iVal == MSG_COM_BLE_GET_CONNECT) {
//            getBleGattC = mBluetoothLeService.getCharacteristic(UUID.fromString(GattAttributeResolver.WFNPS_UUID), UUID.fromString
// (GattAttributeResolver.SSID_CHR_UUID));
            getBleGattC = mBluetoothLeService.getCharacteristic(UUID.fromString(GattAttributeResolver.WFNPS_UUID), UUID.fromString
                    (GattAttributeResolver.CONNECTION_CHR_UUID));
        } else if (iVal == MSG_COM_BLE_GET_SSID) {
            getBleGattC = mBluetoothLeService.getCharacteristic(UUID.fromString(GattAttributeResolver.WFNPS_UUID), UUID.fromString
                    (GattAttributeResolver.SSID_CHR_UUID));
        }
        final int charaProp3 = getBleGattC.getProperties();
        if ((charaProp3 | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            Dlog.v("jino = SendBleOP");
            mBluetoothLeService.readCharacteristic(getBleGattC);
        }
    }

    /**
     * 서버 요청 핸들러.
     */
    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_BLE_GET_CONNECT:
                    dialog_show();
                    Dlog.v("jino = MSG_COM_BLE_GET_CONNECT");
                    SendBleOP(msg.what);
//                    if (getWebSocketState()) {
//                        sendWsDeviceCommand(Constants.WEBSOCKET_COMM_TYPE_UNPAIRING_START);
//                    } else {
//                        comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
//                    }
                    break;

                case MSG_COM_BLE_GET_SSID:
                    SendBleOP(msg.what);
//                    if (getWebSocketState()) {
//                        sendWsDeviceCommand(Constants.WEBSOCKET_COMM_TYPE_PAIRING_STOP);
//                    } else {
//                        comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
//                    }
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
