package chaoran.business.engine.impl;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2021-02-19          FXY        Created
 **********************************************
 */


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
import chaoran.business.engine.BlueToothWrapperEngine;
import chaoran.business.engine.entity.BlueToothSetting;
import com.google.gson.Gson;

import java.lang.reflect.Method;

/**
 * 蓝牙打印机
 */
public class BlueToothPrintEngine extends BlueToothWrapperEngine {

    private Context context;

    //已匹配设备
    private BluetoothDevice match = null;

    private Gson gson;

    public BlueToothPrintEngine(Context context) {
        super(context);
        //初始化
        gson = new Gson();
        this.context = context;

        //广播注册
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        context.registerReceiver(mReceiver, filter);
    }


    @Override
    public void startThenConnect() {
        // 设置蓝牙可见性，最多300秒
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);
        context.startActivity(intent);

        //连接设备
        BlueToothSetting setting = (BlueToothSetting) getSetting();
        String address = setting.getAddress();
        if (null != address && !address.trim().equals("")) {
            BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
            boolean bond = device.createBond();
            if (!bond)
                Toast.makeText(context, "连接设备失败，设备名：" + setting.getName() + " mac：" + setting.getAddress(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void close() {
        bluetoothAdapter.disable();
        context.unregisterReceiver(mReceiver);
    }

    @Override
    public BluetoothDevice getBoundDevice() {
        return match;
    }

    /**
     * 通过广播搜索蓝牙设备
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 把搜索的设置添加到集合中
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //已经匹配的设备
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) { //bond_bonded，已经连接成功，长连接，保持活跃的状态
                    //保存已匹配且是打印机设备的Mac地址
                    if (device.getBluetoothClass().getDeviceClass() == PRINT_TYPE) {
                        saveSetting(new BlueToothSetting(device.getName(), device.getAddress()));
                        match = device;
                    }
                }
            }
        }
    };

    @JavascriptInterface
    public String getStringSetting() {
        return gson.toJson(getSetting());
    }

    @JavascriptInterface
    public void saveSetting(String s) {
        saveSetting(gson.fromJson(s, BlueToothSetting.class));
    }
}

