package com.suixingpay.serialsdk.service;

import android.content.Context;
import android.util.Log;

import com.suixingpay.serialsdk.api.SerialHelper;
import com.suixingpay.serialsdk.api.SerialPortFinder;
import com.suixingpay.serialsdk.bean.ComBean;
import com.suixingpay.serialsdk.listener.SerialListener;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SerialSDKService {

    private static final String TAG = "SerialSDKService";
    private static volatile SerialSDKService instance;

    private SerialHelper serialHelper;
    private SerialPortFinder serialPortFinder;

    private Context context;

    // 打印回调
    private SerialListener serialListener = null;

    public SerialSDKService() {

    }

    /**
     * 单例
     */
    public static SerialSDKService getInstance(Context context) {
        if (instance == null) {
            synchronized (SerialSDKService.class) {
                if (instance == null) {
                    instance = new SerialSDKService();
                }
            }
        }
        instance.context = context;
        return instance;
    }

    public void setListener(SerialListener listener) {
        serialListener = listener;
    }

    /**
     * 创建和初始化
     */
    public void create(String port, int baudRate) {
        if (serialHelper == null) {
            serialHelper = new SerialHelper() {
                @Override
                protected void onDataReceived(final ComBean comBean) {
                    logInfo("onDataReceived ComBean:" + comBean);
                    // 这里是你希望每秒执行的任务
                    String jsonString = new String(comBean.bRec, StandardCharsets.UTF_8);
                    if (!jsonString.isEmpty()) {
                        logInfo("接收到业务数据：" + jsonString);
                        if (serialListener != null) {
                            serialListener.onDataReceived(jsonString);
                        } else {
                            logError("请先设置SerialListener");
                        }
                    }
                }

                @Override
                protected void onDataReceived(String jsonString) {
                    logInfo("onDataReceived 接收到业务数据 jsonString:" + jsonString);
                    if (serialListener != null) {
                        serialListener.onDataReceived(jsonString);
                    } else {
                        logError("请先设置SerialListener");
                    }
                }

                @Override
                protected void onError(int code, String msg) {
                    if (serialListener != null) {
                        serialListener.onError(code, msg);
                    } else {
                        logError("请先设置SerialListener");
                    }

                    logError("SerialHelper onError: :" + "code:" + code + ":" + msg);
                }
            };
        }

        if (serialPortFinder == null) {
            serialPortFinder = new SerialPortFinder();
        }
        // 串口设备的据对路径
        serialHelper.setPort(port);
        // 波特率
        serialHelper.setBaudRate(baudRate);
    }

    public void setStopBits(int stopBits) {
        serialHelper.setStopBits(stopBits);
    }

    public void setDataBits(int stopBits) {
        serialHelper.setDataBits(stopBits);
    }

    public void setParity(int parity) {
        serialHelper.setParity(parity);
    }

    public void setFlowCon(int flowCon) {
        serialHelper.setFlowCon(flowCon);
    }

    /**
     * 设置串口超时时间
     */
    public void setTimeout(int timeout) {
        if (serialHelper != null) {
            serialHelper.setTimeout(timeout);
        }
    }

    /**
     * 串口是否创建
     */
    public boolean isCreate() {
        if (serialHelper == null) {
            logError("SerialHelper 未初始化，请调用createSerial进行创建。");
            return false;
        }
        return true;
    }

    /**
     * 串口是否打开
     */
    public boolean isOpen() {
        if (isCreate()) {
            return serialHelper.isOpen();
        }
        return false;
    }

    /**
     * 打开串口
     */
    public Boolean open() {
        if (isCreate() && !isOpen()) {
            logInfo("开始打开串口");
            try {
                logInfo("开始打开串口");
                serialHelper.open();
                logInfo("串口打开成功");
                return true;
            } catch (Exception e) {
                logError("串口打开失败 : " + e.getMessage(), e);
            }
        }
        return false;
    }

    /**
     * 发送文本消息
     */
    public void sendText(String jsonString) {
        if (isCreate()) {
            if (isOpen()) {
                logInfo("串口已打开，发送的消息是：" + jsonString);
                serialHelper.sendTxt(jsonString);
            } else {
                logError("串口没有打开");
            }
        }
    }

    /**
     * 发送二进制消息
     */
    public void sendHex(String jsonString) {
        if (isCreate()) {
            if (isOpen()) {
                logInfo("串口已打开，发送的消息是：" + jsonString);
                serialHelper.sendHex(jsonString);
            } else {
                logError("串口没有打开");
            }
        }
    }

    /**
     * 关闭串口
     */
    public void close() {
        if (isCreate()) {
            Log.d(TAG, "close");
            serialHelper.close();
        }
    }

    /**
     * 读取所有串口
     */
    public List<String> getAllDevicesPath() {
        if (serialPortFinder != null) {
            final String[] ports = serialPortFinder.getAllDevicesPath();
            return Arrays.asList(ports);
        }
        return Collections.emptyList(); // 返回一个空的不可变列表
    }

    public String getUsbDevicesPath() {
        if (serialPortFinder == null) {
            serialPortFinder = new SerialPortFinder();
        }
        final String[] ports = serialPortFinder.getAllDevicesPath();
        logInfo("ports length:" + ports.length);
        for (String port : ports) {
            logInfo("port:" + port);
            if (port.contains("ttyUSB")) {
                return port;
            }
            if (port.contains("ttyS")) {
                return port;
            }
        }
        return "/dev/ttyUSB0";
    }

    // 日志
    public void logInfo(String msg) {
        Log.i(TAG, msg);
    }

    // 日志
    public void logError(String msg) {
        Log.e(TAG, msg);
    }

    // 日志
    public void logError(String msg, Throwable e) {
        Log.e(TAG, msg, e);
    }
}
