package com.zhimai.websocket.queue;

import com.zhimai.websocket.listener.MessageQueueServiceListner;
import com.zhimai.websocket.util.Logger;
import com.zhimai.websocket.util.RxTimerUtil;
import com.zhimai.websocket.util.SysCode;

/**
 * 队列取消息服务
 */
public class QueueMessageService {
    private static final String TAG = "---QueueMessageService---";
    private static QueueMessageService queueMessageService;
    private boolean isPlay = false;
    private int waiteTime=0;//锁住的等待时间，加一个保护，等待时间过长，直接释放锁
    private int interval = 1000;

    public void setInterval(int interval) {
        this.interval = interval;
    }

    private QueueMessageService() {
    }

    public static QueueMessageService getInstance() {
        if (queueMessageService == null) {
            queueMessageService = new QueueMessageService();
        }
        return queueMessageService;
    }

    public void startPrintService(final MessageQueueServiceListner messageQueueServiceListner) {
        RxTimerUtil.cancel(SysCode.RX_TIMER_TYPE.PRINT);
        RxTimerUtil.interval(SysCode.RX_TIMER_TYPE.PRINT, interval, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext(long number) {
                if (isPlay) {
                    Logger.e(TAG,"-------正在消费消息-------");
                    if(waiteTime>10){
                        Logger.e(TAG,"-------锁定超过10S，自动解锁-------");
                        consumMessage();
                    }else{
                        waiteTime++;
                    }
                    return;
                }
                waiteTime=0;
                Logger.e(TAG,"Queue.length="+MessageQueue.getInstance().QueueLength());
                //如果播报队列不为空，则开始播报
                if (!MessageQueue.getInstance().QueueEmpty()) {
                    //通过接口下放消息
                    if (messageQueueServiceListner != null) {
                        isPlay = true;
                        String message = MessageQueue.getInstance().QueuePeek();
                        Logger.e(TAG,"||||||||||-队列下放消息："+message);
                        messageQueueServiceListner.getMessage(message);
                        //成功下放消息后，队列第一条数据出栈
                        MessageQueue.getInstance().deQueue();
                    } else {
                        Logger.e(TAG, "messageQueueServiceListner==null");
                    }

                }
            }
        });
    }

    /**
     * 消费完一条消息后，调用此方法
     * 注：调用后 服务继续下放消息
     */
    public void consumMessage() {
        //第一条数据出栈
//        MessageQueue.getInstance().deQueue();//根据需要，下放消息时 该消息出栈
        //重置状态,允许再次下放消息
        isPlay = false;
    }
}
