import {IContainer} from "./database/IContainer";
import {SensorType} from "./SensorType";
import {HX711} from "./HX711";
import debug from "debug";

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

export class SensorHelper {

    /**
     * Returns the current container weight
     * @param container
     */
    static measure(container: IContainer): number | null {
        if (container.sensorType == SensorType.LOADCELL) {
            try {
                // V2: Measure weight
                let sensor = new HX711(container.sensorPin1, container.sensorPin2);

                container.rawData = sensor.measure();
            } catch (e) {
                log("Sensor (Weight cell) of container " + container._id + " is broken or has malfunction - Removing it!");
                container.sensorType = SensorType.NONE;
                container.save();
                return null;
            }
        } else if (container.sensorType == SensorType.ULTRASOUND) {
            try {
                // V2: Measure weight
                let sensor = new HX711(container.sensorPin1, container.sensorPin2);

                container.rawData = sensor.measure();

            } catch (e) {
                log("Sensor (Ultrasound) of container " + container._id + " is broken or has malfunction - Removing it!");
                container.sensorType = SensorType.NONE;
                container.save();
                return null;
            }
        }

        // todo Überprüfen ob hier Umrechnungen nötig sind. Soll in Gramm zurück gegeben werden
        return container.rawData;
    }
}