public class DigitalInput {
    private final int pinnya;
    private boolean currentIsON = false;
    private boolean initialized = false;

    /**
     * Buat di JAVA coding
     * @param pin_number : pin
     */
    public DigitalInput(int pin_number) {
       // if (jGPIO.osname=="") jGPIO.detectOS();
        pinnya = pin_number;
        if (Setup_Pin()) {
            initialized = true;
        }
        Runtime.getRuntime().addShutdownHook(new Thread(this::Release));
    }

    private boolean Setup_Pin() {
        if (!GeneralCode.GpioIsExported(pinnya)) {
            // belum ada, coba export dulu
            if (!GeneralCode.ExportGpio(pinnya)) {
                // gagal export
                return false;
            }
        }

        // sampe sini, harusnya ada
        // harus set output dulu
        if (GeneralCode.SetGpioDirection(pinnya, true)) {
            // pasang value 1
            if (GeneralCode.SetGpioValue(pinnya, true)) {
                // ubah jadi input
                if (GeneralCode.SetGpioDirection(pinnya, false)) {
                    System.out.println("DigitalInput Setup_Pin success !!");
                    return true;
                } else System.out.println("Gagal SetDirection ke Input untuk DigitalInput pin "+pinnya);
            } else System.out.println("Gagal SetValue ke high untuk DigitalInput pin "+pinnya);
        } else System.out.println("Gagal SetDirection ke Output untuk DigitalInput pin "+pinnya);
        return false;
    }


    public boolean getIsInitialized(){
        return initialized;
    }


    /**
     * Read State of GPIO
     * @return 0 = Low, 1 = high, -1 = failed reading
     */
    public int ReadState() {
        int value = GeneralCode.GetGpioValue(pinnya);
        if (value==0) {
            currentIsON = false;
        } else if (value==1) {
            currentIsON = true;
        }
        return value;
    }


    /*
     * Get last ReadState value
     * return true if High 1
     * return false if Low  0
     */
    public boolean getIsON(){
        return currentIsON;
    }

    /*
     * Release control of Digital Output (not controlling anymore)
     * return true if success operation
     */
    public void Release() {
        GeneralCode.UnExportGpio(pinnya);
    }

}

