package com.mytatvarnsdk.base;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.Nullable;

import cgmblelib.ble.BleService;
import cgmblelib.database.entity.PocDevice;
import cgmblelib.database.entity.PocGlucose;
import cgmblelib.utils.ConstantsLibrary;
import cgmblelib.utils.MyLog;
import cgmblelib.utils.Tool;
import com.mytatvarnsdk.R;
import com.mytatvarnsdk.myView.popupwindow.PopupWindowManagement;
import com.mytatvarnsdk.myView.progress.ProgressManagement;

import java.util.List;

/**
 * @author Administrator
 * 基础的页面类
 */
public abstract class BaseBleActivity extends BaseLiveDataEventsDistributeActivity implements View.OnClickListener {
    /**
     * 蓝牙服务 --  绑定的服务
     */
    protected BleService mService;
    /**
     * 设备信息
     */
    protected PocDevice mPocDevice;
    /**
     * 全部的数据信息
     */
    protected List<PocGlucose> mPocGlucoses;
    /**
     * 最新的数据信息
     */
    protected PocGlucose mLatestPocGlucose;
    /**
     * 当前APP是否活跃，onCreate的时候设置为true
     */
    private boolean isActive = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!ConstantsLibrary.IS_SCREENSHOT_ABLE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        }
        //屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(setView());
        doBindService();
        // 订阅BLE搜索的回调事件
        subscribeBLEScan();
        // 订阅BLE连接的回调事件
        subscribeBLEConnect();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isActive = true;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//手动调整字体大小后保持不改变
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    /**
     * 开启绑定服务
     */
    private void doBindService() {//OnCreate 中调用
        Intent serviceIntent = new Intent(this, BleService.class);
        if (!bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)) {
            MyLog.w("bindService fail");
        }
    }

    /***
     * 回调，服务绑定
     */
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((BleService.LocalBinder) service).getService();//获得服务实例
            if (mService != null) {
                initOnServiceBind();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    /**
     * 设置页面
     */
    protected abstract int setView();

    /**
     * 在 setView中调用 调用步骤为 1
     */
    protected abstract void initViews();

    /**
     * 在 setView中调用 调用步骤为 2 其上为 initViews()
     */
    protected abstract void init();

    /**
     * 初始化绑定服务的，去除添加的view，重新添加view
     */
    protected void initOnServiceBind() {
        //初始化界面
        initViews();
        //初始化数据
        init();
        isViewAndDataLoaded = true;
    }

    /**
     * Toast 弹出
     *
     * @param resId StringId
     */
    public void showShortToast(int resId) {
        showShortToast(getResources().getString(resId));
    }

    /**
     * Toast 弹出
     *
     * @param text String
     */
    public void showShortToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActive = false;
        PopupWindowManagement.getInstance().dismiss();
        ProgressManagement.getInstance().dismissWait(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        mService = null;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN){
            View currentFocus = getCurrentFocus();
            if (currentFocus!=null){
                if (Tool.isShouldHideKeyboard(currentFocus,ev)){
                    Tool.hideKeyboard(this,currentFocus.getWindowToken());
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public String[][] getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return new String[][]{ConstantsLibrary.BLUETOOTH_S};
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return new String[][]{ConstantsLibrary.LOCAL_PERMISSION,ConstantsLibrary.BACKGROUND_LOCATION_Q};
        } else {
            return new String[][]{ConstantsLibrary.LOCAL_PERMISSION};
        }
    }

    @Override
    public void checkFailForMismatchedSensorAndTransmitter() {
        ProgressManagement.getInstance().dismissWait(this);
        Toast.makeText(this, getString(R.string.qr_wrong), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPermissionRequestFail(String... permission) {
        showLocalPermissionFail();
    }

    @Override
    public void onPermissionRequestFailForever(String... permission) {
        showLocalPermissionFailForever();
    }
}
