package com.suixingpay.serialkit.service;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.suixingpay.serialkit.comm.CommHelper;
import com.suixingpay.serialkit.listener.TppMessageListener;

import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

public class SerialSdkService {

    private static final String TAG = "SerialSdkService";
    private static SerialSdkService instance;
    private CountDownTimer countdownTimer;
    private Timer timer;
    private TimerTask timerTask;
    private TppMessageListener messageListener = null;
    private final Handler handler = new Handler(Looper.getMainLooper());

    // 购物流程控制
    private final Boolean isShopping = false;

    private final Integer shoppingStep = 0;

    private SerialSdkService() {
    }

    public static SerialSdkService getInstance() {
        if (instance == null) {
            instance = new SerialSdkService();
        }
        return instance;
    }

    public void setListener(TppMessageListener listener) {
        this.messageListener = listener;
    }

    public boolean isConnect() {
        return CommHelper.getInstance().isConnect();
    }

    public void connect() {
        CommHelper.getInstance().connect();
        startTimer();
    }

    public void send(String data) {
        CommHelper.getInstance().send(data.getBytes(StandardCharsets.UTF_8));
    }

    private final StringBuilder jsonBuffer = new StringBuilder();

    public String recvNonBlocking() {

        byte[] result = CommHelper.getInstance().recvNonBlocking();

        if (result != null && result.length > 0) {
            String str = new String(result, StandardCharsets.UTF_8);
            logInfo("每次读取到的数据：" + str);
            jsonBuffer.append(str);
        }

        // 尝试获取下一个完整的 JSON 对象
        String jsonString = getNextJson();

        // 如果获取到完整的 JSON，则返回它；否则返回空字符串
        return jsonString != null ? jsonString : "";
    }

    private String getNextJson() {
        if (jsonBuffer.length() == 0) {
            return null; // 如果缓冲区为空，返回 null
        }
        int bracketCount = 0;
        int start = 0;

        // 遍历缓冲区中的字符
        for (int i = 0; i < jsonBuffer.length(); i++) {
            char c = jsonBuffer.charAt(i);

            // 更新括号计数
            if (c == '{') {
                if (bracketCount == 0) {
                    start = i; // 记录开始位置
                }
                bracketCount++;
            } else if (c == '}') {
                bracketCount--;
            }

            // 检测到一个完整的 JSON 对象
            if (bracketCount == 0 && bracketCount >= 0) {
                // 提取完整的 JSON 字符串
                String jsonString = jsonBuffer.substring(start, i + 1).trim();

                // 更新缓冲区，去掉已解析的部分
                String remainingData = jsonBuffer.substring(i + 1);
                jsonBuffer.setLength(0); // 清空缓冲区
                jsonBuffer.append(remainingData); // 仅保留未处理的部分

                return jsonString; // 返回完整的 JSON 字符串
            }
        }

        return null; // 如果没有找到完整的 JSON 对象，返回 null
    }


    public void disConnect() {
        CommHelper.getInstance().disConnect();
        stopTimer();
        cancelCountdownTimer();
    }


    private void startCountdownTimer() {
        handler.post(() -> {
            if (countdownTimer != null) {
                countdownTimer.cancel();
            }
            countdownTimer = new CountDownTimer(CommHelper.getInstance().getRecvTimeout(), 1000) {
                public void onTick(long millisUntilFinished) {
                    Log.i(TAG, "Countdown timer: " + millisUntilFinished / 1000 + " seconds remaining");
                }

                public void onFinish() {
                    logError("Timeout: Calling onError(408, 'Receive data timeout')");
                    if (messageListener != null) {
                        messageListener.onError(408, "Receive data timeout");
                    }
                }
            };
            countdownTimer.start();
        });
    }

    private void cancelCountdownTimer() {
        if (countdownTimer != null) {
            countdownTimer.cancel();
            countdownTimer = null;
        }
    }

    private void startTimer() {
        if (timer == null) {
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    // 这里是你希望每秒执行的任务
                    String jsonString = recvNonBlocking();
                    if (jsonString != null && !jsonString.isEmpty()) {
                        logInfo("APP接收到数据：" + jsonString);
                        cancelCountdownTimer();
                        if (messageListener != null) {
                            messageListener.onDataReceived(jsonString);
                        }
                    } else {
                        logInfo("正在等待接收数据...");
                    }

                }
            };
            // 安排定时任务，延迟0毫秒后每1000毫秒执行一次
            timer.schedule(timerTask, 0, 1000);
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
            timerTask = null;
        }
    }

    public void sendStringNoTimer(String jsonString) {
        logInfo("调用sendStringNoTimer发送消息: " + jsonString);
        sendTextNoTimer(jsonString);
    }

    private void sendTextNoTimer(String data) {
        if (isConnect()) {
            logInfo("POS发送串口数据：" + data);
            send(data);
        } else {
            logError("请先打开串口");
        }
    }

    private void logInfo(String msg) {
        Log.i(TAG, msg);
    }

    private void logError(String msg) {
        Log.e(TAG, msg);
    }
}
