import { MovingHeadState } from 'rust_native_module';
import { Pattern, PatternOutput, RenderUpdate } from './proto';
import { TARGETS } from './stroboInsGesichtLol';
import { startAddresses } from './stage';
import { hsl2rgb, rescale } from './util';
import { Tuple4 } from './types';

export class ChaserPattern implements Pattern {

  lastUpdate: number;
  rgbw: Tuple4<number>;

  constructor() {
    this.lastUpdate = -8;
    this.rgbw = [0, 0, 0, 255];
  }

  render(update: RenderUpdate): PatternOutput {

    if (update.beatRelative === null) {
      this.lastUpdate = -8;
      return null;
    }

    let t = update.beatRelative;

    if (t - this.lastUpdate > 4) {
      this.lastUpdate = Math.floor(t);

      if (Math.random() > 0.2) {

        const h = rescale(Math.random(), { to: [0, 360] });
        const s = 1;
        const l = 0.5;

        const [r, g, b] = hsl2rgb(h, s, l);
        this.rgbw = [
          Math.round(r * 255),
          Math.round(g * 255),
          Math.round(b * 255),
          0
        ]

      } else {
        this.rgbw = [
          0, 0, 0, 255
        ];
      }
    }

    let head_number = Math.floor(t % 4);

    return startAddresses.map((address, index) => {
      const [pan, tilt] = TARGETS[index];

      const state: MovingHeadState = {
        startAddress: address,
        pan: pan,
        tilt: tilt,
        brightness: {
          type: 'dimmer',
          value: 0.1,
        },
        rgbw: this.rgbw,
        speed: 1,
        reset: false
      }

      if (index === head_number) {
        state.brightness = { type: 'dimmer', value: 0.6 };
      }

      return state;
    }) as PatternOutput;

  }
}
