package com.mytatvarnsdk.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.mytatvarnsdk.R;
import com.mytatvarnsdk.base.BaseBleActivity;
import com.mytatvarnsdk.myView.dialog.DialogType;
import com.mytatvarnsdk.myView.dialog.WarnDialog;
import com.mytatvarnsdk.myView.dialog.WarnDialogUtils;
import com.mytatvarnsdk.myView.popupwindow.PopupWindowManagement;
import com.mytatvarnsdk.myView.progress.ProgressManagement;
import com.mytatvarnsdk.myView.progress.ProgressType;
import com.mytatvarnsdk.myView.widget.TransmitterState;

import cgmblelib.Enum.enumDevice;
import cgmblelib.ble.gattcallback.ManageGattCallback;
import cgmblelib.ble.reconnectManagament.ReconnectManagement;
import cgmblelib.ble.scancallback.ManageScanCallback;
import cgmblelib.custom.livedata.scan.PocDeviceAndRssi;
import cgmblelib.database.entity.PocDevice;
import cgmblelib.utils.ConstantsLibrary;
import cgmblelib.utils.MyLog;
import cgmblelib.utils.Tool;

/***
 * 蓝牙页面
 * @author minyuchun
 */
public class BtManageActivity extends BaseBleActivity implements View.OnClickListener {
    /**
     * 开启蓝牙 - requestCode
     */
    public static final int REQUEST_BLUETOOTH_ON = 114;

    public static final int REQUEST_LOCATION_ON = 116;
    /**
     * 进入扫描界面 - requestCode
     */
    public static final int REQUEST_QR = 115;
    /**
     * 发射器列表
     */
    private TransmitterState mBluetoothState;

    private TextView permissionState;

    private SpannableString openBluetoothInfo;
    private SpannableString openLocationInfo;
    private ConstraintLayout group;
    private TextView qrNext;

    private PocDevice connectDevice;

    private TextView title;

//    private String deviceType = "CT3";

    private LinearLayout ll;

    @Override
    protected int setView() {
        return R.layout.activity_bt_manage;
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkBTGPS();
    }

    @Override
    protected void initViews() {
//        deviceType = getIntent().getStringExtra("deviceType");
        ll = findViewById(R.id.rl_pop_bottom);
        permissionState = findViewById(R.id.bt_manage_close_state);
        permissionState.setOnClickListener(this);
        mBluetoothState = findViewById(R.id.transmitter_state);
        ImageView btnLeft = findViewById(R.id.btnLeft);
        btnLeft.setOnClickListener(this);
        findViewById(R.id.btnRight).setVisibility(View.GONE);
        findViewById(R.id.iv_alert_type).setVisibility(View.GONE);
        title = findViewById(R.id.tvTitle);
        title.setText(getString(R.string.title_bt_step1));
        group = findViewById(R.id.qr_group);
        findViewById(R.id.qr_video_enter).setOnClickListener(this);

        qrNext = findViewById(R.id.qr_next);
        qrNext.setOnClickListener(this);

        String blueClosedNote = getResources().getString(R.string.bluetooth_closed);
        openBluetoothInfo = new SpannableString(blueClosedNote);
        openBluetoothInfo.setSpan(
                new ForegroundColorSpan(Color.parseColor("#89C602")),
                blueClosedNote.length() - 11,
                blueClosedNote.length(),
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        String openLocationNote = getResources().getString(R.string.location_permission);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            openLocationNote = getResources().getString(R.string.bluetooth_permission);
        }
        openLocationInfo = new SpannableString(openLocationNote);
        openLocationInfo.setSpan(
                new ForegroundColorSpan(Color.parseColor("#89C602")),
                openLocationNote.length() - 11,
                openLocationNote.length(),
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        //连接发射器
        mBluetoothState.setActivity(this).setOnDeviceConnectionListener(new TransmitterState.OnDeviceConnectionListener() {

            @Override
            public void onDeviceConnect(PocDevice pocDevice, int position) {
                if (pocDevice != null) {
                    Log.d("onDeviceConnect--->", "onDeviceConnect: " + pocDevice.toString());
                }
                connectDevice = pocDevice;
                if (enumDevice.getEnumDevice(pocDevice.getName()).isAbleScanQRCode()) {
                    group.setVisibility(View.VISIBLE);
                    title.setText(getString(R.string.title_bt_step2));
                    mBluetoothState.hind(true);
                    PopupWindowManagement.getInstance().dismiss();
                } else {
                    bind(pocDevice);
                    mPocDevice = pocDevice;
                    PopupWindowManagement.getInstance().dismiss();
                }
            }

            @Override
            public void onQRResult(int type, PocDevice pocDevice, int position) {
            }
        });
        requestPermission();
    }

    @Override
    protected void init() {
    }


    public void checkBTGPS() {
        if ((group == null || group.getVisibility() == View.GONE) && permissionState != null) {
            if (getDeniedPermissions() == null) {
                if (Tool.getBluetoothAdapter(getApplicationContext()).getState() == BluetoothAdapter.STATE_ON && Tool.isGPSEnable_S(this)) {
                    permissionState.setVisibility(View.GONE);
                    mBluetoothState.setVisibility(View.VISIBLE);
                    scanDeviceAgain();
                } else {
                    permissionState.setVisibility(View.VISIBLE);
                    mBluetoothState.setVisibility(View.GONE);
                    if (Tool.getBluetoothAdapter(getApplicationContext()).getState() == BluetoothAdapter.STATE_OFF) {
                        permissionState.setText(openBluetoothInfo);
                        WarnDialogUtils.getInstance().showWarnDialog(this, DialogType.POP_BT_OPEN, getResources().getString(R.string.bluetooth_closed), null, new WarnDialog.OnSelectListener() {
                            @Override
                            public void confirm(DialogInterface dialog) {
                                Tool.ableBluetooth(BtManageActivity.this, REQUEST_BLUETOOTH_ON);
                                dialog.dismiss();
                            }

                            @Override
                            public void cancel(DialogInterface dialog) {
                                dialog.dismiss();
                            }
                        }, null);
                    } else if (!Tool.isGPSEnable_S(this)) {
                        permissionState.setText(openLocationInfo);
                    }
                }
            } else {
                permissionState.setVisibility(View.VISIBLE);
                mBluetoothState.setVisibility(View.GONE);
                permissionState.setText(openLocationInfo);
            }
        }
    }

    @Override
    public void onPermissionRequestSuccess() {
        permissions = null;
        if (group.getVisibility() == View.GONE) {
            checkBTGPS();
        } else {
            if (connectDevice != null) {
                //todo Ankit - review this code
            }
        }
    }

    @Override
    public void scanStart() {
        mBluetoothState.refresh(null, null);
        mBluetoothState.transmitterImg.startAnimation(Tool.getRotate());
    }


    @Override
    public void scanIn(PocDeviceAndRssi device) {
        MyLog.i("scanIn " + device.toString());
        mBluetoothState.setVisibility(View.VISIBLE);
        mBluetoothState.refresh(device, null);
    }

    @Override
    public void scanEnd() {
        mBluetoothState.transmitterImg.clearAnimation();
        mBluetoothState.transmitterImg.setVisibility(View.GONE);
        mBluetoothState.loadSuccess();
    }

    @Override
    public void bluetoothStateOFF() {
        checkBTGPS();
        showShortToast(R.string.please_open_bluetooth);
    }

    @Override
    public void bluetoothStateON() {
        checkBTGPS();
    }

    @Override
    public void failGPS() {
        checkBTGPS();
        warn_gpsFail();
    }

    @Override
    public void failLocal() {
        checkBTGPS();
    }

    @Override
    public void bindFail() {
        mBluetoothState.notifyItem();
        ProgressManagement.getInstance().dismissWait(this);
    }

    @Override
    public void bindSuccess() {
        //todo Ankit - review this code
        ProgressManagement.getInstance().dismissWait(this);
        finish();
    }


    @Override
    public void disconnect() {
        mBluetoothState.notifyItem();
        ProgressManagement.getInstance().dismissWait(this);
        showShortToast(R.string.bt_connect_fail);
    }

    @Override
    public void disconnectForTimeout() {
        mBluetoothState.notifyItem();
        ProgressManagement.getInstance().dismissWait(this);
        showShortToast(R.string.bt_connect_fail);
    }

    @Override
    public void checkFailForLowPower() {
        mBluetoothState.notifyItem();
        ProgressManagement.getInstance().dismissWait(this);
        WarnDialogUtils.getInstance().showWarnDialog(this, DialogType.TYPE_LOW_POWER);
    }

    @Override
    public void checkFailErrorTemperature() {
        mBluetoothState.notifyItem();
        ProgressManagement.getInstance().dismissWait(this);
    }

    @Override
    public void onlineLost() {
        showShortToast(R.string.online_lost);
    }

    /**
     * 搜索发射器,点击搜索按钮
     */
    public void scanDeviceAgain() {
        if (mPocDevice == null || !mPocDevice.isBound()) {
            WarnDialogUtils.getInstance().dismissWarnDialog();
            ReconnectManagement.getInstance().reconnect(ReconnectManagement.ReconnectState.STATE_SCAN_AGAIN);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();//关闭发射器
        if (id == R.id.btnLeft) {
            finish();
        } else if (id == R.id.bt_manage_close_state) {
            permissionOpen();
        } else if (id == R.id.qr_next) {
            requestPermission();
        }
    }


    private float downY = -1;

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        if (downY == -1) {
            downY = e.getRawY();
        }
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = e.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                float gap = (e.getRawY() - downY) / 2;
                downY = e.getRawY();
                mBluetoothState.isNoTouch = false;
                if (!mBluetoothState.recyclerView.canScrollVertically(-1)) {
                    mBluetoothState.clearUpAnimation();
                    mBluetoothState.setUpHeightVisible(gap);
                }
                break;
            default:
                downY = -1;
                mBluetoothState.isNoTouch = true;
                if (!mBluetoothState.recyclerView.canScrollVertically(-1)) {
                    mBluetoothState.startUpAnimation(mBluetoothState.upstate);
                }
                break;
        }
        return super.onTouchEvent(e);
    }

    private void permissionOpen() {
        if (permissions != null) {
            requestPermissions(permissions);
        } else {
            BluetoothAdapter adapter = Tool.getBluetoothAdapter(this);
            if (adapter != null && !adapter.isEnabled()) {
                Tool.ableBluetooth(this, REQUEST_BLUETOOTH_ON);
            } else if (!Tool.isGPSEnable_S(this)) {
                Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(settingsIntent);
            } else {
                checkBTGPS();
            }
        }
    }

    @Override
    public String[][] getPermission() {
        MyLog.i("获取版本 " + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return new String[][]{ConstantsLibrary.BLUETOOTH_S, ConstantsLibrary.CAMERA_PERMISSION};
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return new String[][]{ConstantsLibrary.LOCAL_PERMISSION, ConstantsLibrary.BACKGROUND_LOCATION_Q, ConstantsLibrary.CAMERA_PERMISSION};
        } else {
            return new String[][]{ConstantsLibrary.LOCAL_PERMISSION, ConstantsLibrary.CAMERA_PERMISSION};
        }
    }


    @SuppressLint("BatteryLife")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_QR) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    mPocDevice = data.getParcelableExtra("device");
                    if (mPocDevice != null) {
                        bind(mPocDevice);
                    }
                }
            } else {
                mBluetoothState.isConnecting = false;
                MyLog.e("扫描失败");
            }
        } else if (requestCode == REQUEST_BLUETOOTH_ON) {
            if (resultCode == RESULT_OK) {
                scanDeviceAgain();
            }
        } else if (requestCode == REQUEST_LOCATION_ON) {
            if (resultCode == RESULT_OK) {
                scanDeviceAgain();
            }
        }
    }

    /**
     * 进行设备绑定
     *
     * @param device 需要绑定的发射器
     */
    private void bind(PocDevice device) {
        MyLog.setLocalLog(device.getId(), device.getName());
        MyLog.iLog("bind result");
        if (device.getAddress() != null) {
            ManageGattCallback.getInstance().ConnectViaAddress(device.getAddress());
            ManageScanCallback.getInstance().stopLeScan();
            ProgressManagement.getInstance().showWait(this, ProgressType.PROGRESSDIALOG_CONNECT, null);
        }
    }

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