package com.sunzee.thread.generalparameter;

import com.hboxs.serialport.SerialPortSendQueue;
import com.hboxs.serialport.frame.ReadCommandFrame;
import com.hboxs.serialport.frame.RstCommandFrame;
import com.hboxs.serialport.frame.SetCommandFrame;

/**
 * 通用参数任务
 */
public class GeneralParameterTask implements Runnable {

    private int type;
    private volatile String address;

    public String getAddress() {
        return address;
    }

    public int getId() {
        return id;
    }

    private volatile int id;
    private volatile boolean isRun;
    private String name;
    private String data;

    public GeneralParameterTask(int type) {
        clearPlcQuee();
        this.type = type;
    }

    public GeneralParameterTask(int type, String address) {
        clearPlcQuee();
        this.type = type;
        this.address = address;
    }

    public GeneralParameterTask(int type, String address, int id) {
        clearPlcQuee();
        this.type = type;
        this.address = address;
        this.id = id;
    }


    public GeneralParameterTask(int type, String address, String data, int id, String name) {
        clearPlcQuee();
        this.type = type;
        this.address = address;
        this.data = data;
        this.id = id;
        this.name = name;
    }

    private void clearPlcQuee() {
        setIsRun(true);
        SerialPortSendQueue.clear();
    }

    public void setIsRun(boolean isRun) {
        this.isRun = isRun;
    }

    public boolean getIsRun() {
        return isRun;
    }

    @Override
    public void run() {
        switch (type) {
            case GeneralParameterThreadType.runM17:
                runReadM17();
                break;
            case GeneralParameterThreadType.runRst:
                runRst();
                break;
            case GeneralParameterThreadType.runSet:
                runSet();
                break;

        }
    }

    private void runReadM17() {
        if (getIsRun()) {
            SerialPortSendQueue.sendCommand(new ReadCommandFrame("M17", 2), 17, "M17");
        }
    }

    private void runSet() {
        if (getIsRun()) {
            SerialPortSendQueue.sendCommand(new SetCommandFrame(address), 18, address);
        }
    }

    private void runRst() {
        if (getIsRun()) {
            SerialPortSendQueue.sendCommand(new RstCommandFrame(address), 18, address);
        }
    }

    public void setAddressAndId(String address, int id) {
        this.address = address;
        this.id = id;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
