import ws281x from "rpi-ws281x-native";
import {Utils} from "./Utils";

export class LEDHandler {
    private static channel = ws281x(100, {stripType: 'ws2812'});
    private static currentInterval: NodeJS.Timer | undefined;

    public static pulseBlue() {
        clearInterval(this.currentInterval);
        const colors = this.channel.array;
        for (let i = 0; i < colors.length; i++) {
            colors[i] = 0x02f5f5;
        }
        this.channel.brightness = 50;
        ws281x.render();

        this.currentInterval = setInterval(async () => {
            for (let i = 50; i <= 255; i++) {
                this.channel.brightness = i;
                await Utils.sleep(10);
            }
            await ws281x.render();
            await Utils.sleep(300);
            for (let i = 255; i >= 50; i--) {
                this.channel.brightness = i;
                await Utils.sleep(10);
            }
        }, 4500);

    }

    public static doGreen() {
        clearInterval(this.currentInterval);
        const colors = this.channel.array;
        for (let i = 0; i < colors.length; i++) {
            colors[i] = 0x419822;
        }
        this.channel.brightness = 255;
        ws281x.render();
    }


    public static clear() {
        clearInterval(this.currentInterval);
        this.currentInterval = undefined;
    }

    static init(): Promise<void> {
        return new Promise<void>(async (resolve) => {
            const options = {
                dma: 10,
                freq: 800000,
                gpio: 18,
                invert: false,
                brightness: 255,
                stripType: ws281x.stripType.WS2812
            };

            this.channel = ws281x(20, options);

            setInterval(this.loop, 1000);
            resolve();
        });
    }

    private static loop(): Promise<void> {
        return new Promise<void>((resolve) => {
            if (this.currentInterval)
                return;

            LEDHandler.ambientColor();
            resolve();
        });
    }

    private static ambientColor() {
        const colors = this.channel.array;
        for (let i = 0; i < colors.length; i++) {
            colors[i] = 0xd60007;
        }
        this.channel.brightness = 255;
        ws281x.render();
    }
}