package aicare.net.cn.sdk.ailinksdkdemoandroid.modules.toothbrush;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.bean.BleValueBean;
import com.pingwang.bluetoothlib.config.CmdConfig;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.device.wifibleDevice.WifiBleDeviceData;
import com.pingwang.bluetoothlib.device.wifibleDevice.WifiBleInfoBean;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;
import com.pingwang.bluetoothlib.utils.BleLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.DialogStringImageBean;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.MoveDataDialogFragment;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.ShowListDialogFragment;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.L;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.TimeUtils;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.ToothBrushUtils;
import cn.net.aicare.modulelibrary.module.ToothBrush.ToothBrushBleCmd;
import cn.net.aicare.modulelibrary.module.ToothBrush.ToothBrushWiFiBleUtilsData;

/**
 * Wifi+ble 牙刷
 */
public class ToothBrushWifiOnOnBleActivity extends BleBaseActivity implements View.OnClickListener, OnCallbackBle, WifiBleDeviceData.OnWiFiBleCallback, ToothBrushWiFiBleUtilsData.OnBleToothBrushCallback {
    private String TAG = ToothBrushWifiOnOnBleActivity.class.getName();
    private String mAddress;
    private List<String> mList;
    private ArrayAdapter listAdapter;

    private ToothBrushWiFiBleUtilsData mToothBrushWiFiBleUtilsData;
    private MHandler mMHandler;
    private EditText select_gears_et, ed_score;
    private List<DialogStringImageBean> mWifiList = new ArrayList<>();
    private List<WifiBleInfoBean> mWifiBleInfoBeanList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横屏
        setContentView(R.layout.activity_tooth_brush_wifi_ble);
        findViewById(R.id.getWifiStatus).setOnClickListener(this);
        findViewById(R.id.getSn).setOnClickListener(this);
        findViewById(R.id.scanWifi).setOnClickListener(this);
        findViewById(R.id.disconnectWifi).setOnClickListener(this);
        findViewById(R.id.getWifiName).setOnClickListener(this);
        findViewById(R.id.getSupportUnit).setOnClickListener(this);
        findViewById(R.id.defaultTryOut).setOnClickListener(this);
        findViewById(R.id.getTimeMode).setOnClickListener(this);
        findViewById(R.id.defaultMode).setOnClickListener(this);
        findViewById(R.id.ota).setOnClickListener(this);
        findViewById(R.id.btnScore).setOnClickListener(this);

        select_gears_et = findViewById(R.id.etSelectGears);
        ed_score = findViewById(R.id.etScore);

        mAddress = getIntent().getStringExtra("mac");
        mList = new ArrayList<>();
        ListView listView = findViewById(R.id.log_list);
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        listView.setAdapter(listAdapter);
        WeakReference weakReference = new WeakReference(new MHandler());
        mMHandler = (MHandler) weakReference.get();


    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (mToothBrushWiFiBleUtilsData != null) {
            if (id == R.id.getWifiStatus) {
                mToothBrushWiFiBleUtilsData.getWifiCurrentState();
            } else if (id == R.id.getSn) {
                mToothBrushWiFiBleUtilsData.getDeviceId();
            } else if (id == R.id.scanWifi) {
                mToothBrushWiFiBleUtilsData.scanWifi();
                mList.add(TimeUtils.getTime() + "正在扫描附近可用的wifi...");
                mMHandler.sendEmptyMessage(TO_REFRESH_UI);
                showWifiList();
            } else if (id == R.id.getWifiName) {
                mToothBrushWiFiBleUtilsData.getConnectWifiName();
            } else if (id == R.id.disconnectWifi) {
                mToothBrushWiFiBleUtilsData.disconnectWifi();
            } else if (id == R.id.getSupportUnit) {
                mToothBrushWiFiBleUtilsData.getSupportGears();
            } else if (id == R.id.defaultMode) {
                String gear = select_gears_et.getText().toString().trim();
                if (!gear.isEmpty()) {
                    String[] gears = null;
                    if (gear.contains(",")) {
                        gears = gear.split(",");
                    } else if (gear.contains("，")) {
                        gears = gear.split("，");
                    } else {
                        Toast.makeText(this, "请输入时长,档位,档位级别(数字加符号)", Toast.LENGTH_SHORT).show();
                    }
                    if (gears != null) {
                        try {
                            mToothBrushWiFiBleUtilsData.setDefault(Integer.parseInt(gears[0]), Integer.parseInt(gears[1]), Integer.parseInt(gears[2]));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            Toast.makeText(this, "请输入时长,档位,档位级别(数字加符号)", Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            } else if (id == R.id.defaultTryOut) {
                String gear1 = select_gears_et.getText().toString().trim();
                if (!gear1.isEmpty()) {
                    String[] gears = null;
                    if (gear1.contains(",")) {
                        gears = gear1.split(",");
                    } else if (gear1.contains("，")) {
                        gears = gear1.split("，");
                    } else {
                        Toast.makeText(this, "请输入时长,档位,档位级别(数字加符号)", Toast.LENGTH_SHORT).show();
                    }
                    if (gears != null) {
                        try {
                            mToothBrushWiFiBleUtilsData.setTryOut(Integer.parseInt(gears[1]), Integer.parseInt(gears[2]), 0, 0);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            Toast.makeText(this, "请输入时长,档位,档位级别(数字加符号)", Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            } else if (id == R.id.getTimeMode) {
                mToothBrushWiFiBleUtilsData.getDefaultGearAndDuration();
            } else if (id == R.id.ota) {
                showFileChooser();
                //                    mToothBrushWiFiBleUtilsData.setOta();
            }
        }
        if (v.getId() == R.id.btnScore) {
            try {
                String[] time = ed_score.getText().toString().trim().split(",");
                int defaultTime = Integer.parseInt(time[0]);
                int useTime = Integer.parseInt(time[1]);
                int lTime = Integer.parseInt(time[2]);
                int rTime = Integer.parseInt(time[3]);
                ToothBrushUtils toothBrushUtils = new ToothBrushUtils();
                int grade = toothBrushUtils.getGrade(defaultTime, useTime, lTime, rTime);
                int avg = toothBrushUtils.getAvgGrade(defaultTime, lTime, rTime);
                int rang = toothBrushUtils.getRangeGrade(defaultTime, lTime, rTime);
                int duration = toothBrushUtils.getDurationGrade(defaultTime, useTime);
                mList.add(0, grade + " 均匀度: " + avg + "  范围：" + rang + "  刷牙时长：" + duration);
                mMHandler.sendEmptyMessage(TO_REFRESH_UI);
            } catch (Exception e) {

                mList.add(0, "出错了 请按 默认时长,刷牙时长,左时长,右时长.输入单位是秒");
                mMHandler.sendEmptyMessage(TO_REFRESH_UI);
                e.printStackTrace();
            }
        }
    }


    private ShowListDialogFragment mShowListDialogFragment;

    private void showWifiList() {
        if (mShowListDialogFragment == null) {
            mShowListDialogFragment = ShowListDialogFragment.newInstance();
            mShowListDialogFragment.setList(mWifiList);
            mShowListDialogFragment.setTitle("选择WIFI");
            mShowListDialogFragment.setCancel("取消", 0);
            mShowListDialogFragment.setOnDialogListener(new ShowListDialogFragment.onDialogListener() {
                @Override
                public void onItemListener(int position) {
                    WifiBleInfoBean wifiBleInfoBean = mWifiBleInfoBeanList.get(position);
                    String ssid = wifiBleInfoBean.getSsid();
                    MoveDataDialogFragment.newInstance()
                            .setTitle(ssid, "")
                            .setContent("", "请输入密码", MoveDataDialogFragment.NAME)
                            .setOk("OK", 0)
                            .setCancel("取消", 0)
                            .setOnDialogListener(new MoveDataDialogFragment.OnDialogListener() {
                                @Override
                                public void onSucceedListener(View v, String data) {
                                    String pwd = data.trim();
                                    setConnectWifi(wifiBleInfoBean.getMac(), pwd);

                                }
                            })
                            .show(getSupportFragmentManager());
                }

                @Override
                public void onCancelListener(View v) {

                }
            });
        }
        mShowListDialogFragment.show(getSupportFragmentManager());
    }

    /**
     * 设置连接wifi
     *
     * @param mac mac
     * @param pwd 密码
     */
    private void setConnectWifi(String mac, String pwd) {
        if (mToothBrushWiFiBleUtilsData != null) {
            mToothBrushWiFiBleUtilsData.setConnectWifiMac(mac, pwd);
            mList.add(TimeUtils.getTime() + "正在连接wifi...");
            mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        }
    }


    @Override
    public void onServiceSuccess() {

        //与服务建立连接
        mList.add(0, "服务与界面建立连接成功");
        //        mList.add(0, "搜索设备");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        mAILinkBleManager.setOnCallbackBle(this);

    }


    @Override
    public void onServiceErr() {

    }

    @Override
    public void unbindServices() {
        if (mAILinkBleManager != null) {
            mAILinkBleManager.removeOnCallbackBle(this);
            mAILinkBleManager.disconnectAll();
        }
    }


    @Override
    public void onScanning(BleValueBean data) {
        BleLog.i(TAG, "MAC=" + mAddress + "||CID=" + data.getCid() + "||VID=" + data.getVid() + "||PID=" + data.getPid());
        if (data.getMac().equalsIgnoreCase(mAddress)) {
            if (mAILinkBleManager != null) {
                mAILinkBleManager.stopScan();
                mAILinkBleManager.connectDevice(data);
            }
        }
    }

    @Override
    public void onDisConnected(String mac, int code) {
        if (mAddress.equalsIgnoreCase(mac)) {
            mList.add(0, "蓝牙已断开:" + mac);
            mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        }
    }

    @Override
    public void onServicesDiscovered(String mac) {
        if (mAddress.equalsIgnoreCase(mac)) {
            mList.add(0, "蓝牙已连接");
            mMHandler.sendEmptyMessage(TO_REFRESH_UI);
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                ToothBrushWiFiBleUtilsData.init(bleDevice, this, this);
                mToothBrushWiFiBleUtilsData = ToothBrushWiFiBleUtilsData.getInstance();
                mMHandler.sendEmptyMessageDelayed(TO_REQUEST_TOKEN, 600);
                mMHandler.sendEmptyMessageDelayed(GET_BATTERY, 800);
            }
        }
    }

    @Override
    public void bleOpen() {
        if (mAILinkBleManager != null) {
            mAILinkBleManager.startScan(30000L);
        }
        mList.add(0, "蓝牙已开启,开始搜索连接");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void bleClose() {
        mList.add(0, "蓝牙已关闭");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    @Override
    public void onBleAndWifiStatus(int bleStatus, int wifiStatus, int workStatus) {
        BleLog.e(TAG, "蓝牙状态：" + bleStatus + " wifi状态：" + wifiStatus + " 工作状态：" + workStatus);
        mList.add(0, "蓝牙状态：" + bleStatus + " wifi状态：" + wifiStatus + " 工作状态：" + workStatus);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onWifiScanStatus(int status) {
        mList.add(0, "扫描wifi状态: " + status);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onConnectWifiName(String name) {
        mList.add(0, "当前连接wifi名称: " + name);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    @Override
    public void onWifiScanBean(WifiBleInfoBean wifiBleInfoBean) {
        mList.add(0, "扫描到wifi: " + wifiBleInfoBean.toString());
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onWifiScanFinish(List<WifiBleInfoBean> list) {
        mList.add(0, "扫描结束 扫描的wifi个数 " + list.size());
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        if (mWifiBleInfoBeanList == null) {
            mWifiBleInfoBeanList = new ArrayList<>();
        }
        mWifiBleInfoBeanList.clear();
        mWifiList.clear();
        for (WifiBleInfoBean wifiBleInfoBean : list) {
            String ssid = wifiBleInfoBean.getSsid();
            if (TextUtils.isEmpty(ssid)) {
                continue;
            }
            mWifiList.add(new DialogStringImageBean(ssid, wifiBleInfoBean.getType()));
            mWifiBleInfoBeanList.add(wifiBleInfoBean);
        }
        if (mShowListDialogFragment != null) {
            mShowListDialogFragment.setList(mWifiList);
        }
    }


    @Override
    public void onSetWifiNameOrPwdOrConnectCallback(int type, int status) {
        if (type == CmdConfig.SET_WIFI_MAC) {
            mList.add(0, "获取到设置的mac地址状态 " + status);
        }
        if (type == CmdConfig.SET_WIFI_PWD) {
            mList.add(0, "获取到设置的密码状态 " + status);
        }
        if (type == CmdConfig.DIS_OR_CON_WIFI) {
            mList.add(0, "发起连接 " + status);
        }
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onWifiConnecting(int status) {
        WifiBleDeviceData.OnWiFiBleCallback.super.onWifiConnecting(status);
    }

    @Override
    public void onConnectWifiMac(String mac) {
        mList.add(0, "获取到设置的wifi的mac地址 " + mac);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onConnectWifiPwd(String pwd) {
        mList.add(0, "获取到设置的wifi的密码 " + pwd);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onDeviceSn(long sn) {
        mList.add(0, "sn: " + sn);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onServerIp(String ip) {
        mList.add(0, "ip: " + ip);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onServerPort(int port) {
        mList.add(0, "port: " + port);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onServerPath(String path) {
        mList.add(0, "path: " + path);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    /**
     * 关于服务器设置信息
     *
     * @param status 状态 true 配置完成, false 配置失败
     */
    @Override
    public void onServerSettingInfo(boolean status) {
        mList.add(0, "服务器设置信息: " + (status ? "配置完成" : "配置失败"));
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    private final int TO_REFRESH_UI = 300;
    private final int CONNECT_WIFI = 400;
    private final int TO_REQUEST_TOKEN = 500;
    private final int GET_BATTERY = 600;


    @Override
    public void onVersion(String version) {
        mList.add(0, "版本号:" + version);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onGetSupportGears(List<Integer> staif, List<Integer> secondLevel) {
        mList.add(0, "牙刷支持的一级档位:" + Arrays.toString(staif.toArray()) + " 二级档位:" + Arrays.toString(secondLevel.toArray()));
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onGetBattery(int batteryStatus, int batteryQuantity) {
        mList.add(0, "电池状态:" + batteryStatus + " 电量:" + batteryQuantity);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onGetDefaultGearAndDuration(int time, int gear, int gearFrom) {
        mList.add(0, "获得到默认的刷牙档位和时长:" + time + " 档位:" + gear + " 档位级别" + gearFrom);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onGetTokenResult(int result) {
        String s = "";
        if (result == ToothBrushBleCmd.NO_TOKEN) {
            s = "没有";
        } else if (result == ToothBrushBleCmd.HAS_TOKEN) {
            s = "已经授权";
        } else if (result == ToothBrushBleCmd.WITHOUT_TOKEN) {
            s = "不需要授权";
        } else if (result == ToothBrushBleCmd.SUCCESSTOKEN) {
            s = "授权成功";
        }
        mList.add(0, "请求授权结果" + result + "  " + s);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onGetManualParameter(int time, int hz, int duty) {
        mList.add(0, " 获取手动档位的参数: 时长" + time + "  频率" + hz + "   占空比" + duty);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onSetDefaultModeAndManualModeResult(byte type, int result) {
        String s = "";
        if (result == 0) {
            s = "设置成功";
        } else if (result == 1) {
            s = "设置失败";
        } else if (result == 2) {
            s = "不支持设置";
        }
        if (type == ToothBrushBleCmd.SET_TOOTHBRUSH_TIME_GEARS) {
            mList.add(0, " 设置默认刷牙时长和工作档位: 结果" + result + "  " + s);
            mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        } else {
            mList.add(0, "  设置手动设置（自定义）档位: 结果" + result + "  " + s);
            mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        }
    }

    @Override
    public void onTestFinish(int totalTime, int leftTime, int rightTime, int mode, int battery) {
        mList.add(0, "刷牙完成: 总时长:" + totalTime + " 左时长:" + leftTime + " 右时长:" + rightTime + " 模式:" + mode + " 电量:" + battery);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onTryOutResult(int result) {
        mList.add(0, "设置使用结果:" + result + " ( 0：设置成功 1：设置失败，原因未知 2：不支持设置)");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onTwoLevelModeDefault(int mode) {
        mList.add(0, "获取二级档位默认值:" + mode);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    @Override
    public void onOTA(int status) {
        String s = " ";
        switch (status) {
            case 0x00:
                s = "wifiOTA 成功";
                break;
            case 0x01:
                s = "wifiOTA 失败";
                break;
            case 0x02:
                s = "不支持 wifiOTA";
                break;
            case 0x03:
                s = "模块主动开始 wifiOTA（MCU 收到该指 令后不能断电，需要等待 OTA 成功或者失败）";
                break;
        }
        mList.add(0, s);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    @Override
    public void onGetApiKey(String apiKey) {
        ToothBrushWiFiBleUtilsData.OnBleToothBrushCallback.super.onGetApiKey(apiKey);
    }

    @Override
    public void onSetApiKey(boolean result) {
        ToothBrushWiFiBleUtilsData.OnBleToothBrushCallback.super.onSetApiKey(result);
    }

    @Override
    public void onShowData(String data) {
        L.i(data);
    }

    private class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TO_REFRESH_UI:
                    if (listAdapter != null) {
                        listAdapter.notifyDataSetChanged();
                    }
                    break;
                case CONNECT_WIFI:
                    mToothBrushWiFiBleUtilsData.setConnectWifi();
                    break;
                case TO_REQUEST_TOKEN:
                    mList.add(0, "请求授权");
                    mToothBrushWiFiBleUtilsData.requestToken(System.currentTimeMillis());
                    if (listAdapter != null) {
                        listAdapter.notifyDataSetChanged();
                    }
                    mToothBrushWiFiBleUtilsData.getDefaultGearAndDuration();
                    break;
                case GET_BATTERY:
                    mToothBrushWiFiBleUtilsData.getBattery();
                    break;
            }
        }
    }


    private static final int FILE_SELECT_CODE = 0x1002;

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            String path = uri.getPath();
            mList.add(0, "ota准备就绪，请勿操作");
            listAdapter.notifyDataSetChanged();
//            initOtaUtil(this, uri, new OnBleOTAListener() {
//                @Override
//                public void onOtaSuccess() {
//                    mList.add(0, "ota成功");
//                    listAdapter.notifyDataSetChanged();
//
//                }
//
//                @Override
//                public void onOtaFailure(int cmd, String err) {
//                    mList.add(0, "失败");
//                    listAdapter.notifyDataSetChanged();
//                }
//
//                private int mOldProgress = -1;
//
//                @Override
//                public void onOtaProgress(float progress, int currentCount, int maxCount) {
//                    if (mOldProgress != progress) {
//                        mOldProgress = (int) progress;
//                        mList.add(0, "otaProgress:" + progress);
//                        listAdapter.notifyDataSetChanged();
//                    }
//                }
//            }, mToothBrushWiFiBleUtilsData.getBleDevice());
        } else {

        }
    }


//    private OPLOtaManager mOPLOtaManager;
//
//    public void initOtaUtil(Context context, Uri url, OnBleOTAListener listener, BleDevice bleDevice) {
//        mOPLOtaManager = null;
//        mOPLOtaManager = OPLOtaManager.newBuilder(context).setFileUri(url).setOnBleOTAListener(listener).build(bleDevice);
//        mOPLOtaManager.startOta();
//    }

}
