package com.henrypump.poc;

/**
 * Created by patrickjmcd on 2/10/17.
 */
public class IOControl implements Runnable {

    private final POC poc;
    private DigitalIn startBtn, stopBtn;
    private DigitalOut led2, led3, led4, led5;
    private DigitalOut runningIndicator, runCommand;
    private double pos = 0;
    private int runStatus;

    IOControl(POC poc){
        this.poc = poc;
        // IO
        startBtn = new DigitalIn(8);
        stopBtn = new DigitalIn(9);
        led2 = new DigitalOut(2, 0);
        led3 = new DigitalOut(3, 0);
        led4 = new DigitalOut(4, 0);
        led5 = new DigitalOut(5, 0);
        runningIndicator = new DigitalOut(6,0);
        runCommand = new DigitalOut(7,0);
    }

    private void startWell(){
        poc.thisWell.start("startbutton");
    }

    private void stopWell(){
        poc.thisWell.stop("startbutton");
    }

    private void exitPOC(){
        poc.thisWell.db.newRunStatus("Shutdown", "io");
        allOutputsOff();
        System.exit(0);
    }

    public void allOutputsOff(){
        led2.write(0,true);
        led3.write(0,true);
        led4.write(0,true);
        led5.write(0,true);
        runningIndicator.write(0, true);
        runCommand.write(0,true);
    }

    public void run() {
        System.out.println("Running the IOControl Loop");
        for (;;) {
            if (startBtn.read() == 1) startWell();
            if (stopBtn.read() == 1) stopWell();
            if (startBtn.read() == 1 && stopBtn.read() == 1) {
                exitPOC();
            }

            pos = poc.thisWell.getCurrentSurfacePosition();
            runStatus = poc.thisWell.getRunStatus();
            led2.write(pos > 20.0 ? 1 : 0);
            led3.write(pos > 40.0 ? 1 : 0);
            led4.write(pos > 60.0 ? 1 : 0);
            led5.write(pos > 80.0 ? 1 : 0);

            runningIndicator.write(runStatus == Well.RUNSTATUS_RUNNING ? 1 : 0);
            runCommand.write((runStatus == Well.RUNSTATUS_RUNNING || runStatus == Well.RUNSTATUS_STARTING) ? 1 : 0);
        }
    }
}
