package com.unibuy.smartdevice.controller;

import com.unibuy.smartdevice.devices.DeviceType;
import com.unibuy.smartdevice.devices.PortTools;
import com.unibuy.smartdevice.devices.UsbDev;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.tools.HandlerMain;

public class DevBarCodeController extends DevController {
    private Logs logs;
    private UsbDev usbDev;
    public DevBarCodeController(HandlerMain handlerMain) {
        super(20, handlerMain);
        this.logs = new Logs(getClass());
        try {
            this.usbDev = new UsbDev(DeviceType.QRCODE_SCANNER);
        } catch (LogsEmptyException | LogsUnsupportedOperationException | LogsIOException e) {
//            getLogs().warning(e);
            getLogs().warning(e);
        }
    }

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

    @Override
    protected void close(HandlerMain handlerMain) {
        try {
            usbDev.closePort();
        } catch (LogsIOException e) {
//            getLogs().warning(e);
            getLogs().warning(e);
        }
    }

    @Override
    protected void execute(HandlerMain handlerMain) {
        try {
            while (isRun() && isReadBufferMax()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                byte[] buffer = new byte[20];
                int size = usbDev.read(buffer, 1000);
                if (size > 0) {
                    setRun(false);
                    byte[] code = PortTools.catByteArrays(buffer, 0, size);
                    publishReadBuffer(code);
                }
            }
        } catch (LogsUnsupportedOperationException | LogsIOException e) {
            getLogs().warning(e);
        }
    }

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