import GPIO from "rpi-gpio";
import Container from "./database/Container";
import debug from "debug";
import {IContainer} from "./database/IContainer";

const log = debug("itender:gpio");

// Package is raspi-gpio in raspberrypi

export class MyGPIO {
    static setup(pin: number, direction): Promise<void> {
        return new Promise((resolve, reject) => {
            try {
                GPIO.setup(pin, direction, (err) => {
                    if (err) {
                        reject();
                        return;
                    }
                    resolve();
                });
            } catch (e) {
                reject(e);
            }
        })
    }

    static write(pin: number, state: boolean): Promise<void> {
        return new Promise((resolve, reject) => {
            try {
                GPIO.write(pin, state, (err) => {
                    if (err) {
                        reject();
                        return;
                    }
                    resolve();
                });
            } catch (e) {
                reject(e);
            }
        });
    }

    static setupPins(): Promise<void> {
        log("Setting up GPIO-Pins...");
        return new Promise(async resolve => {
            let containers = await Container.find({});
            for (let c of containers) {
                try {
                    if (c.sensorType && !c.useProxy) {
                        await MyGPIO.setup(c.sensorPin1, GPIO.DIR_IN);
                        await MyGPIO.setup(c.sensorPin2, GPIO.DIR_IN);
                    }
                    if( c.pumpPin && !c.useProxy )
                    {
                        await MyGPIO.setup(c.pumpPin, GPIO.DIR_OUT);
                        await MyGPIO.write(c.pumpPin, false);
                    }
                } catch (e) {
                }
            }
            resolve();
        });
    }
}