package com.hh.lib_dx_base_multi.serialport;


import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.donsee.devices.CardReader;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_dx_base_multi.DxCardReader;
import com.hh.lib_dx_base_multi.DxInitListener;
import com.hh.lib_dx_base_multi.bean.InitStatusEnum;
import com.hh.lib_dx_base_multi.serialport.listener.ReadCPUCardListener;
import com.hh.lib_dx_base_multi.serialport.listener.ReadM1CardListener;

import java.util.HashMap;

/**
 * @author xwh
 * time 2024/9/13
 * Description: 东信多合一串口
 **/
public class DxSerialportCardReader {
    private volatile static DxSerialportCardReader instance;

    private CardReader cardReader;
    private volatile InitStatusEnum statusEnum = InitStatusEnum.DEFAULT;//设备是否初始化

    private static final int MESSAGE_RETRY_READER = 0x99; //重连
    private Handler mHandler;
    private volatile HashMap<String, DxInitListener> initListenerMap;
    private CReaderThread cReaderDataThread;
    private volatile boolean isRuning = false;

    private volatile ReadCPUCardListener cpuCardListener;
    private volatile ReadM1CardListener readM1CardListener;

    public Handler getmHandler() {
        if (mHandler == null) {
            synchronized (DxCardReader.class) {
                if (mHandler == null) {
                    mHandler = new Handler(Looper.getMainLooper()) {
                        @Override
                        public void handleMessage(Message msg) {
                            switch (msg.what) {
                                case MESSAGE_RETRY_READER:
                                    initCardReader();
                                    break;
                                default:
                                    break;
                            }
                            super.handleMessage(msg);
                        }
                    };
                }
            }
        }
        return mHandler;
    }

    public static DxSerialportCardReader getInstance() {
        if (instance == null) {
            synchronized (DxSerialportCardReader.class) {
                if (instance == null) {
                    instance = new DxSerialportCardReader();

                }
            }
        }
        return instance;
    }

    /**
     *
     * @author xwh
     * Time 2024/11/5
     * Description: 初始化
     *
    **/
    public synchronized void init(Context context, String clazzName, DxInitListener listener) {
        if (initListenerMap == null) {
            initListenerMap = new HashMap<>();
        }
        if (!TextUtils.isEmpty(clazzName) && listener != null) {
            initListenerMap.put(clazzName, listener);
        }
        if (cardReader == null) {
            synchronized (DxSerialportCardReader.class) {
                if (cardReader == null) {
                    cardReader = new CardReader(context);
                    initCardReader();
                }
            }
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/11/5
     * Description: 初始化东信读卡器-串口模式
     *
    **/
    private synchronized void initCardReader() {
        synchronized (DxSerialportCardReader.class) {
            if (cardReader == null) {
                return;
            }
            try {
                long result = cardReader.Donsee_Open("/dev/ttysWK0");
                if (result == 0) {
                    statusEnum = InitStatusEnum.SUCCESS;
                    initListenerCallback(true, "", "");
                    startRead();
                } else {
                    if (statusEnum != InitStatusEnum.FAIL) {
                        statusEnum = InitStatusEnum.FAIL;
                        initListenerCallback(false, result + "", "读卡器初始化失败");
                        stopRead();
                    }
                    getmHandler().removeMessages(MESSAGE_RETRY_READER);
                    getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READER, 5000);
                }
            } catch (Exception e) {
                getmHandler().removeMessages(MESSAGE_RETRY_READER);
                getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READER, 5000);
            }
        }

    }

    /**
     * @author xwh
     * Time 2024/10/10
     * Description: 初始化结果回调
     **/
    private void initListenerCallback(boolean isInitSucced, String code, String errMsg) {
        if (initListenerMap == null) {
            return;
        }
        for (String key : initListenerMap.keySet()) {
            DxInitListener listener = initListenerMap.get(key);
            if (listener != null) {
                if (isInitSucced) {
                    listener.initSuccess();
                } else {
                    listener.initFailed(code, errMsg);
                }
            }
        }

    }


    public CardReader getCardReader() {
        return cardReader;
    }

    /**
     * @author xwh
     * Time 2024/9/13
     * Description: 是否初始化成功
     **/
    public boolean isInitSuccessed(){
        return statusEnum==InitStatusEnum.SUCCESS;
    }

    public InitStatusEnum getStatusEnum() {
        return statusEnum;
    }


    public void setCpuCardListener(ReadCPUCardListener cpuCardListener) {
        this.cpuCardListener = cpuCardListener;
    }

    public void setReadM1CardListener(ReadM1CardListener readM1CardListener) {
        this.readM1CardListener = readM1CardListener;
    }

    /**
     * @author xwh
     * Time 2024/9/13
     * Description: 销毁资源
     **/
    public synchronized void release() {
        stopRead();
        if (cardReader != null) {
            cardReader.Donsee_Close();
            cardReader.unregisterUSBReceiver();
            cardReader = null;
        }
        instance = null;

    }



    /**
     *
     * desc:启动东信读卡器轮询
     * @author xia weihao
     * @date 2024/6/26
     *
     */
    public synchronized void startRead() {
        if (cReaderDataThread != null && cReaderDataThread.isAlive()) {
            return;
        }
        if (cReaderDataThread != null) {
            isRuning = false;
            cReaderDataThread.interrupt();
            cReaderDataThread = null;
        }
        if (cReaderDataThread == null) {
            cReaderDataThread = new CReaderThread();
        }
        isRuning = true;
        cReaderDataThread.start();

    }

    /**
     *
     * desc:停止东信读卡器读取
     * @author xia weihao
     * @date 2024/6/26
     *
     */
    public synchronized void stopRead() {
        if (cReaderDataThread == null) {
//            showString("请先启动读卡");
            return;
        }
        isRuning = false;
        cReaderDataThread.pause = false;
        cReaderDataThread.interrupt();
        cReaderDataThread = null;
    }
    private class CReaderThread extends Thread {
        private final Object lock = new Object();
        private volatile boolean pause = false;

        public CReaderThread() {
        }

        void pauseThread() {
            pause = true;
        }

        void resumeThread() {
            pause = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            super.run();
            while (isRuning) {
                try {//后面这些N个try是给性能没那么好的cpu预留的  没啥特殊需求就留着
                    while (pause) onPause();
                    if (statusEnum != InitStatusEnum.SUCCESS) {
                        Thread.sleep(500);
                        continue;
                    }
                    if(cpuCardListener!=null){
                        cpuCardListener.readNFC();
                    }
                    Thread.sleep(200);
                    if(readM1CardListener!=null){
                        readM1CardListener.readM1();
                    }
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    isRuning = false;
                    cReaderDataThread = null;
                    e.printStackTrace();
                }
            }
        }
    }


}
