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.c_interface.ListInterface;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * <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 HomehubBleStep4 extends CustomActivity implements View.OnClickListener
        , ListInterface
        , CustomDialog.OnMsgAlterToResult {

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

    private static final int MSG_COM_BLE_SET_SCAN = 1;
    private static final int MSG_COM_BLE_GET_APLIST1 = 2;
    private static final int MSG_COM_BLE_GET_APLIST2 = 3;
    private static final int MSG_COM_BLE_GET_APLIST3 = 4;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 99999999;
    private static final int CONNECT_MAX_TIME_SEC = 60;
    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 HomehubBleStep4Adapter mHomehubBleStep4Adapter;
    private boolean mIsLoading = false;
    private boolean mIsDestroy = false;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Intent mIntent;
    private Animation mLoadingAnimation;
    private Handler mHandler = new Handler();
    private boolean mScanning;
    private ScheduledFuture mScheduledFuture;
    private Boolean mIsEnd = false;
    private Boolean mIsPollingPause = false;
    private Boolean mIsPollingCancel = false;
    private int mMaxTime = CONNECT_MAX_TIME_SEC;
    private int mTotal = 0;
    private int mSelectIdx = -1;
    Runnable runnable = new Runnable() {
        public void run() {

            Dlog.v("Things mIsPollingCancel", mIsPollingCancel);
            Dlog.v("Things mIsPollingPause", mIsPollingPause);
            if (mIsPollingCancel) {
                mIsLoading = false;
                mScheduledFuture.cancel(false);
            }
            if (!mIsPollingPause) {
                mTotal++;
                mUtil.getTextView(mActivity, R.id.tvConnectTime).post(new Runnable() {
                    @Override
                    public void run() {

                        mUtil.getTextView(mActivity, R.id.tvConnectTime).setText((mMaxTime - mTotal) + "");
                    }
                });
                if (mTotal >= mMaxTime) {
                    Dlog.v("jino113 mIsLoading" + mIsLoading);
                    if (mIsLoading) {
                        Dlog.v("jino113 mIsLoading" + mIsLoading);
                        mIsLoading = false;
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                final Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {

                                        if (!mIsDestroy) {
                                            mSwipeRefreshLayout.setEnabled(true);
                                            mUtil.getView(mActivity, R.id.rlProgressLoading).setVisibility(View.INVISIBLE);
                                            mUtil.getTextView(mActivity, R.id.tvLoadingMsg).setText(R.string.layout_homehub_ble_step4_03);
                                            if (mScheduledFuture != null) {
                                                mIsPollingPause = true;
                                                mScheduledFuture.cancel(false);
                                            }
                                            mUtil.getTextView(mActivity, R.id.tvConnectTime).setText("");
                                            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_GET_APLIST1), Constants
                                                    .HANDLER_DELAY_MILLIS);
                                        }
                                    }
                                }, 1000);

                            }
                        });

                        mScheduledFuture.cancel(false);
                    }
                }
            }
        }
    };

    private BluetoothLeService mBluetoothLeService;
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            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 boolean mDiscovered = false;

    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));
            Dlog.v("jino data = " + data);
            if (uuid.equals(GattAttributeResolver.WLAN_LIST1_CHR_UUID)) {
                if (!data.equals("")) {
                    addItem(data);
                }
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_GET_APLIST2), Constants.HANDLER_DELAY_MILLIS);
            } else if (uuid.equals(GattAttributeResolver.WLAN_LIST2_CHR_UUID)) {
                if (!data.equals("")) {
                    addItem(data);
                }
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_GET_APLIST3), Constants.HANDLER_DELAY_MILLIS);
            } else if (uuid.equals(GattAttributeResolver.WLAN_LIST3_CHR_UUID)) {
                if (!data.equals("")) {
                    addItem(data);
                }
                if (mAlTotalList.size() == 0) {
                    mIntent = new Intent(mActivity, HomehubBleStep4Err.class);
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOMEHUB_BLE_STEP4_ERR);
                }
            }

//            if (device.getName() != null) {
//                if (device.getName().contains("DKC")) {
//                    HashMap<String, Object> hmItem = new HashMap<String, Object>();
//                    hmItem.put(Constants.KEY_NAME, device.getName());
//                    hmItem.put(Constants.KEY_ADDRESS, device.getAddress());
//                    hmItem.put(Constants.KEY_CONNECTION, "N");
//                    hmItem.put(Constants.KEY_LOADING, "N");
//                    addItem(hmItem);
//                    mHomehubBleStep4Adapter.notifyDataSetChanged();
//                }
//            }
//            mDataField.setText(data);
        }
    }

    /**
     * 검색된 디바이스를 adapter에 추가.
     *
     * @param item 검색된 디바이스 정보
     */
    public void addItem(String item) {

        try {
            JSONObject jsonObject = new JSONObject(item);
            JSONArray jsonArray = new JSONArray(jsonObject.getString(Constants.KEY_WLAN));
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                HashMap<String, Object> hmTempDevice = new HashMap<String, Object>();
                hmTempDevice = mUtil.jsonToMap(jsonObj);
                hmTempDevice.put(Constants.KEY_SELECT_YN, "N");
                mAlTotalList.add(hmTempDevice);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (mAlTotalList.size() > 0) {
            mUtil.getView(mActivity, R.id.rvHomhubList).setVisibility(View.VISIBLE);
            mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.VISIBLE);
        }
        mHomehubBleStep4Adapter.notifyDataSetChanged();
    }

    /**
     * 홈허브 리스트 초기화.
     */
    public void clearItem() {
        this.mAlTotalList.clear();
        mSelectIdx = -1;
        mUtil.getView(mActivity, R.id.rvHomhubList).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.GONE);
        mHomehubBleStep4Adapter.notifyDataSetChanged();
    }

    /**
     * 노드 추가 60초 타이머 스케줄러.
     */
    private void setPolling() {

        mSwipeRefreshLayout.setRefreshing(false);
        mTotal = 0;
        Dlog.v("Things setThingsDelPolling");
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        mIsPollingPause = false;
        mIsPollingCancel = false;
        mScheduledFuture = scheduler.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);

        mSwipeRefreshLayout.setEnabled(false);
        mUtil.getView(mActivity, R.id.rlProgressLoading).setVisibility(View.VISIBLE);
        mUtil.getTextView(mActivity, R.id.tvLoadingMsg).setText(R.string.layout_homehub_ble_step4_02);
    }

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


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

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

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

        setToolbar();
        viewInit();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            CheckPermission();
        } else {
            startLoading();
        }

    }

    @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 {
            startLoading();
        }
    }

    @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");
                    startLoading();
                } 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_STEP5:
                case Constants.ACT_HOMEHUB_BLE_STEP4_ERR:
                    Boolean isRetry = data.getBooleanExtra(Constants.EXTRA_RETRAY_FLAG, false);
                    if (isRetry) {
                        startLoading();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEHUB_BLE_STEP5:
                case Constants.ACT_HOMEHUB_BLE_STEP4_ERR:
                    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()");
        if (mScheduledFuture != null) {
            mIsPollingPause = true;
            mScheduledFuture.cancel(false);
        }
        unbindService(mServiceConnection);
        mBluetoothLeService = null;

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llBtn1:
                if (mSelectIdx > -1) {
                    mIntent = new Intent(mActivity, HomehubBleStep5.class);
                    mIntent.putExtra(Constants.KEY_SSID, mUtil.null2string(mAlTotalList.get(mSelectIdx).get(Constants.KEY_SSID)));
                    mIntent.putExtra(Constants.KEY_SECURITY, mUtil.null2string(mAlTotalList.get(mSelectIdx).get(Constants.KEY_SECURITY)));
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOMEHUB_BLE_STEP5);
                }
                break;
            case R.id.llBtn2:
//                mCustomDialog.msgAlert(mActivity, Constants.MSG905);
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {
        switch (msgId) {
            case Constants.MSG905:
                if (btnResult == 1) {
                    onBackPressedEnd();
                }
                break;
            case Constants.MSG941:
                if (btnResult == 1) {
                    onBackPressedEnd();
                }
                break;
            case Constants.MSG939:
                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.llBtn1).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);

        mHomehubBleStep4Adapter = new HomehubBleStep4Adapter(mAlTotalList, this);
        LinearLayoutManager llManager = new LinearLayoutManager(mActivity);
        RecyclerView rvHomehubList = (RecyclerView) findViewById(R.id.rvHomhubList);
        rvHomehubList.setLayoutManager(llManager);
        rvHomehubList.setAdapter(mHomehubBleStep4Adapter);

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayou);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipeRefreshLayout.setRefreshing(false);
                Dlog.v("jino113 mIsLoading" + mIsLoading);
                if (!mIsLoading) {
                    clearItem();
                    startLoading();
                }
            }
        });
    }

    /**
     * 툴바 셋팅.
     */
    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_step4_01));
    }

    /**
     * 로딩 이미지 애니메이션 시작.
     */
    private void startLoading() {
        setPolling();
        Dlog.v("jino113 mIsLoading" + mIsLoading);
        mIsLoading = true;
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_BLE_SET_SCAN), Constants.HANDLER_DELAY_MILLIS);

    }

    public void SendBleOP(int iVal) {
        if (iVal == MSG_COM_BLE_SET_SCAN) {
            mBluetoothLeService.writeToCharacteristic(UUID.fromString(GattAttributeResolver.WFNPS_UUID), UUID.fromString
                    (GattAttributeResolver.SCAN_CHR_UUID), new byte[]{(byte) 0x01});
        } else if (iVal == MSG_COM_BLE_GET_APLIST1) {
            BluetoothGattCharacteristic getBleGattC1 = mBluetoothLeService.getCharacteristic(UUID.fromString(GattAttributeResolver
                    .WFNPS_UUID), UUID.fromString(GattAttributeResolver.WLAN_LIST1_CHR_UUID));

            int charaProp1 = getBleGattC1.getProperties();
            if ((charaProp1 | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                mBluetoothLeService.readCharacteristic(getBleGattC1);
            }
        } else if (iVal == MSG_COM_BLE_GET_APLIST2) {
            BluetoothGattCharacteristic getBleGattC2 = mBluetoothLeService.getCharacteristic(UUID.fromString(GattAttributeResolver
                    .WFNPS_UUID), UUID.fromString(GattAttributeResolver.WLAN_LIST2_CHR_UUID));

            int charaProp2 = getBleGattC2.getProperties();
            if ((charaProp2 | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                mBluetoothLeService.readCharacteristic(getBleGattC2);
            }

        } else if (iVal == MSG_COM_BLE_GET_APLIST3) {
            BluetoothGattCharacteristic getBleGattC3 = mBluetoothLeService.getCharacteristic(UUID.fromString(GattAttributeResolver
                    .WFNPS_UUID), UUID.fromString(GattAttributeResolver.WLAN_LIST3_CHR_UUID));

            int charaProp3 = getBleGattC3.getProperties();
            if ((charaProp3 | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                mBluetoothLeService.readCharacteristic(getBleGattC3);
            }
        }
    }

    @Override
    public void onListReload() {

//        mLoading = true;
//        if (setHomeHubStateList()) {
//            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICES), 10);
//        }
    }

    @Override
    public void onLogout() {
        //        mCallback.onLogout();
    }

    @Override
    public void onCallAction(int callType, int position) {

        // 디바이스 목록이 없으면 아래 코드 수행하지 않음.
        Dlog.v("jino111");
        if (mAlTotalList.size() <= 0) {
            Dlog.v("jino112");
            return;
        }
        Dlog.v("jino117");
        if (callType == 0) {
            //추가하기
        } else if (callType == 1) {
            for (int i = 0; i < mAlTotalList.size(); i++){
                mAlTotalList.get(i).put(Constants.KEY_SELECT_YN, "N");
            }
            mAlTotalList.get(position).put(Constants.KEY_SELECT_YN, "Y");
            mSelectIdx = position;
            mHomehubBleStep4Adapter.notifyDataSetChanged();
        } else if (callType == 2) {
            // 삭제하기
        } else if (callType == 3) {
            // 실행하기
        }
    }

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

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_BLE_SET_SCAN:
                    Dlog.v("jino = MSG_COM_BLE_SET_SCAN");
                    SendBleOP(msg.what);
                    break;
                case MSG_COM_BLE_GET_APLIST1:
                    Dlog.v("jino = MSG_COM_BLE_GET_APLIST1");
                    SendBleOP(msg.what);
                    break;
                case MSG_COM_BLE_GET_APLIST2:
                    Dlog.v("jino = MSG_COM_BLE_GET_APLIST2");
                    SendBleOP(msg.what);
                    break;
                case MSG_COM_BLE_GET_APLIST3:
                    Dlog.v("jino = MSG_COM_BLE_GET_APLIST3");
                    SendBleOP(msg.what);
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
