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.c_interface.ListInterface;
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.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
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.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
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 java.util.ArrayList;
import java.util.HashMap;
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 HomehubBleStep2 extends CustomActivity implements View.OnClickListener
        , ListInterface
        , CustomDialog.OnMsgAlterToResult {

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

    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<>();
    CountDownTimer timer;
    private Activity mActivity;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private HomehubBleStep2Adapter mHomehubBleStep2Adapter;
    private boolean mIsLoading = false;
    private boolean mIsDestroy = false;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Intent mIntent;
    private Handler mHandler = new Handler();
    private ScheduledFuture mScheduledFuture;
    private Boolean mIsPollingPause = false;
    private Boolean mIsPollingCancel = false;
    private boolean mConnected = false;
    private boolean mDiscovered = false;
    private int mMaxTime = CONNECT_MAX_TIME_SEC;
    private int mTotal = 0;
    private BluetoothLeService mBluetoothLeService;
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

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

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
    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;
                getDiscoverServices();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                Log.v("jino", "disconnected");
                mConnected = false;
                mDiscovered = false;
                if (timer != null) {
                    timer.cancel();
                    timer.onFinish();
                } else {
                    checkNextStep();
                }
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                Dlog.v("jino ACTION_GATT_SERVICES_DISCOVERED");
//                displayGattServices(mBluetoothLeService.getSupportedGattServices());
                mDiscovered = true;
                timer.cancel();
                timer.onFinish();
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }
        }
    };
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    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);
                            mHomehubBleStep2Adapter.notifyDataSetChanged();
                        }
                    }
                }
            });
        }
    };
    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 (mAlTotalList.size() > 1) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            final Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    //add your code here
                                    mCustomDialog.msgAlert(mActivity, Constants.MSG941);
                                }
                            }, 1000);

                        }
                    });
                    mIsLoading = false;
                    mScheduledFuture.cancel(false);
                    //여기서 2개 이상 오류 발생시킴
                }
                if (mTotal >= mMaxTime) {
                    Dlog.v("jino113 mIsLoading" + mIsLoading);
                    if (mIsLoading) {
                        Dlog.v("jino113 mIsLoading" + mIsLoading);
                        mIsLoading = false;
                        mUtil.getTextView(mActivity, R.id.tvConnectTime).post(new Runnable() {
                            @Override
                            public void run() {

                                if (!mIsDestroy) {
                                    scanLeDevice(false);
                                    mSwipeRefreshLayout.setEnabled(true);
                                    mUtil.getView(mActivity, R.id.rlProgressLoading).setVisibility(View.INVISIBLE);
                                    mUtil.getTextView(mActivity, R.id.tvLoadingMsg).setText(R.string.layout_homehub_ble_step2_04);
                                    mUtil.getTextView(mActivity, R.id.tvLoadingMsg1).setText(R.string.layout_homehub_ble_step2_05);
                                }
                                mUtil.getTextView(mActivity, R.id.tvConnectTime).setText("");
                                if (mScheduledFuture != null) {
                                    mIsPollingPause = true;
                                    mScheduledFuture.cancel(false);
                                }
                                //실패 화면 호출
                                if (mAlTotalList.size() == 0) {
//                                mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.INVISIBLE);
                                    mIntent = new Intent(mActivity, HomehubBleStep2Err.class);
                                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOMEHUB_BLE_STEP2_ERR);
                                } else if (mAlTotalList.size() == 1) {
                                    mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.VISIBLE);
                                }
                            }
                        });

                        mScheduledFuture.cancel(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 getDiscoverServices() {


        //타이머 설정
        timer = new CountDownTimer(SCAN_PERIOD, 1000) {
            @Override
            public void onFinish() {
                checkNextStep();
            }

            @Override
            public void onTick(long millisUntilFinished) {

            }
        };

        //타이머 시작
        timer.start();
        mDiscovered = false;
        mBluetoothLeService.discoverServices();
    }

    private void checkNextStep() {
        dialog_dismiss();
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //add your code here
                        if (mDiscovered) {
                            mIntent = new Intent(mActivity, HomehubBleStep3.class);
                            mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOMEHUB_BLE_STEP3);
                        } else {
                            // 여기서 오류 발생시켜야 함.
                            mCustomDialog.msgAlert(mActivity, Constants.MSG939);
                        }
                    }
                }, 1000);

            }
        });
    }

    private void displayData(String data) {
        if (data != null) {
            Log.v("jino getdata", data);
        }
    }

    /**
     * 검색된 디바이스를 adapter에 추가.
     *
     * @param item 검색된 디바이스 정보
     */
    public void addItem(HashMap<String, Object> item) {
//        Dlog.i("addItem : " + item.toString());
        if (!mAlTotalList.contains(item)) {
            Dlog.i("addItem : " + mUtil.null2string(item.get(Constants.KEY_NAME)));
            if (mUtil.getView(mActivity, R.id.rvHomhubList).getVisibility() == View.GONE) {
                mUtil.getView(mActivity, R.id.rvHomhubList).setVisibility(View.VISIBLE);
            }
            mAlTotalList.add(item);
            mHomehubBleStep2Adapter.notifyDataSetChanged();
        }
    }

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

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

        mSwipeRefreshLayout.setRefreshing(false);
        mTotal = 0;
        Dlog.v("Things setPolling");
        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_step2_02);
        mUtil.getTextView(mActivity, R.id.tvLoadingMsg1).setText(R.string.layout_homehub_ble_step2_03);
    }

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


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

        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.homehub_ble_step2, 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();
        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_HOMEHUB_BLE_STEP3:
                case Constants.ACT_HOMEHUB_BLE_STEP2_ERR:
                    Boolean isRetry = data.getBooleanExtra(Constants.EXTRA_RETRAY_FLAG, false);
                    if (isRetry) {
                        startLoading();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEHUB_BLE_STEP3:
                case Constants.ACT_HOMEHUB_BLE_STEP2_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;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

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

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

        Dlog.v("onDestroy()");
        scanLeDevice(false);
        if (mScheduledFuture != null) {
            mIsPollingPause = true;
            mScheduledFuture.cancel(false);
        }
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
        if (timer != null) {
            timer.cancel();
        }
        timer = null;

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llBtn1:
                if (mAlTotalList.size() == 1) {
                    dialog_show();
                    mBluetoothLeService.connect1(mUtil.null2string(mAlTotalList.get(0).get(Constants.KEY_ADDRESS)));
                }
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    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
    public void resultCustomDialogResponse(int msgId, int btnResult) {
        switch (msgId) {
            case Constants.MSG905:
                if (btnResult == 1) {
                    onBackPressedFlowEnd();
                }
                break;
            case Constants.MSG941:
                if (btnResult == 1) {
                    onBackPressedFlowEnd();
                }
                break;
            case Constants.MSG939:
                if (btnResult == 1) {
                    onBackPressedFlowEnd();
                }
                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);

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

        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_step2_01));
    }

    /**
     * 로딩 이미지 애니메이션 시작.
     */
    private void startLoading() {
        setPolling();
        Dlog.v("jino113 mIsLoading" + mIsLoading);
        mIsLoading = true;
        scanLeDevice(true);
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);

            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }


    @Override
    public void onListReload() {

    }

    @Override
    public void onLogout() {

    }

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

        // 디바이스 목록이 없으면 아래 코드 수행하지 않음.
        Dlog.v("jino111");
        if (mAlTotalList.size() <= 0) {
            Dlog.v("jino112");
            return;
        }

        Dlog.v("jino113 mIsLoading" + mIsLoading);
        if (mIsLoading) {
            Dlog.v("jino114");
            return;
        }

        Dlog.v("jino115");
//        if (mScheduledFuture != null) {
//            Dlog.v("jino116");
//            return;
//        }

        Dlog.v("jino117");
        if (callType == 0) {
            //추가하기
        } else if (callType == 1) {

        } else if (callType == 2) {
            // 삭제하기
        } else if (callType == 3) {
            // 실행하기
        }
    }
}
