package com.unibuy.smartdevice.controller;

import com.unibuy.smartdevice.devices.ComPort;
import com.unibuy.smartdevice.devices.DevDigitalDisplay;
import com.unibuy.smartdevice.devices.Rs232Dev;
import com.unibuy.smartdevice.exception.ErrorCode;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.tools.HandlerMain;

public class DevDigitalDisplayController extends DevController {
    private Rs232Dev comPort;

    public DevDigitalDisplayController(HandlerMain handlerMain) {
        super(10, handlerMain);
        try {
            this.comPort = new Rs232Dev(ComPort.COM_PORT_6);
        } catch (LogsUnsupportedOperationException | LogsIOException e) {
//            getLogs().warning(e);
            getLogs().warning(e);
        }
    }

    public void devPut(int slot, int h, int m, int min) throws LogsIOException {
        byte[] buffer = DevDigitalDisplay.getBuffer(slot, h, m, min);
        addSendBuffer(buffer);
    }

    @Override
    protected void close(HandlerMain handlerMain) {
        try {
            if (this.comPort != null) {
                this.comPort.closePort();
            }
        } catch (LogsIOException e) {
            getLogs().warning(e);
        }
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return getSrcHandlerMain();
    }

    @Override
    protected void execute(HandlerMain handlerMain) {
        try {
            while (isRun() && getCountBySendBuffer() == 0) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            if (isRun() && getCountBySendBuffer() > 0) {
                while (isRun() && getCountBySendBuffer() > 0) {
                    this.comPort.send(getSendBufferByFirst());
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    removeSendBufferByFirst();
                    byte[] readBuffer = this.comPort.readListen(100, 5);
                    if (readBuffer.length > 0) {
                        publishReadBuffer(readBuffer);
                    }
                }
            }
        } catch (LogsIOException e) {
//            getLogs().warning(e);
            getLogs().warning(e);
        }
    }

//    @Override
//    protected void exception(ErrorCode errorCode, String message, HandlerMain handlerMain) {
//        handlerMain.error(getClass().getSimpleName(), errorCode, message);
//        setRun(false);
//    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }
}
