public class DigitalOutput {
    int pin;
    boolean initState;
    boolean initialized;
    DigitalOutput(int pinOut,boolean initialiaState) {
        pin = pinOut;
        initState = initialiaState;
        initialized = Setup_Pin();
        Runtime.getRuntime().addShutdownHook(new Thread(this::Release));
    }

    private boolean Setup_Pin() {
        if (!GeneralCode.GpioIsExported(pin)) {
            // belum ada, coba export dulu
            if (!GeneralCode.ExportGpio(pin)) {
                // gagal export
                System.out.println("GW EDIT DI BAGINI INI NIH!!");
                return false;

            }
        }
        // set direction first
        if (GeneralCode.SetGpioDirection(pin, true)) {
            // pasang value 1
            if (GeneralCode.SetGpioValue(pin, initState)) {
                System.out.println("DigitalOutput Setup_Pin success !!");
                return true;
            } else System.out.println("Gagal SetValue ke high untuk DigitalInput pin "+pin);
        } else System.out.println("Gagal SetDirection ke Output untuk DigitalInput pin "+pin);
        return false;
    }

    public void SetHigh(){
        if (!initialized) {
            System.out.println("Pin is not initialized");
            return;
        }
        GeneralCode.SetGpioValue(pin,true);
    }

    public void SetLow(){
        if (!initialized){
            System.out.println("Pin is not initialized");
            return;
        }
        GeneralCode.SetGpioValue(pin,false);
    }

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