package com.henrypump.poc;

/**
 * Created by patrickjmcd on 2/1/17.
 */

import mraa.Dir;
import mraa.Aio;
import mraa.mraa;
import mraa.Platform;
import mraa.Result;

import static java.lang.Thread.sleep;


public class AnalogIn {
    private int channel;
    private Aio gpioPin;
    private double lastValue;
    private double rawMin;
    private double rawMax;
    private double euMin;
    private double euMax;
    private double[] history = new double[100];

    AnalogIn(int channel, double rawMin, double rawMax, double euMin, double euMax){
        this.channel = channel;
        if (channel != 99) {
            Platform platform = mraa.getPlatformType();
            if (platform != Platform.INTEL_EDISON_FAB_C) {
                System.err.println("Error: This program can only be run on edison");
                System.exit(Result.ERROR_INVALID_PLATFORM.swigValue());
            }
            this.gpioPin = new Aio(this.channel);
        }

        this.rawMax = rawMax;
        this.rawMin = rawMin;
        this.euMax = euMax;
        this.euMin = euMin;
    }

    public double getHistory(int pointIndex) {
        return history[pointIndex];
    }

    public long readRaw(){
        return gpioPin.read();
    }

    public double readScaled(){
        double pv  = ((euMax - euMin)/(rawMax - rawMin)) * gpioPin.read() + (euMax - ((euMax - euMin)/(rawMax - rawMin)) * rawMax);
        lastValue = pv;
        for(int i = 98; i >= 0; i--){
            history[i+1] = history[i];
        }
        history[0] = lastValue;
        return pv;
    }

    public double readScaledSim(double simRaw){
        double pv  = ((euMax - euMin)/(rawMax - rawMin)) * simRaw + (euMax - ((euMax - euMin)/(rawMax - rawMin)) * rawMax);
        lastValue = pv;
        for(int i = 98; i >= 0; i--){
            history[i+1] = history[i];
        }
        history[0] = lastValue;
        return pv;
    }

    public static void main(String[] args){
        System.out.println("Testing Analog Inputs Inputs...");
        boolean forceEnd = false;
        AnalogIn testIn0 = new AnalogIn(0, 0, 1020, 0, 4.6);

        do {
            try{
                System.out.println("Raw = " + testIn0.readRaw());
                System.out.println("Scaled = " + testIn0.readScaled());
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (!forceEnd);
    }
}
