/**
 * Relabi generator UI
 * @module src/ui/App.js;
 */

import * as React from "react";
import { useState, useEffect, useRef } from "react";
import Relabi from "../relabi";
import { Kalimba, Drums } from "../lib/instruments";
import Controls from "./Controls.jsx";

export default function App() {
  const [relabi, setRelabi] = useState();
  const relabiRef = useRef();

  /**
   * Instantiate the Relabi generator
   */
  useEffect(() => {
    if (!relabi) {
      const relabiGenerator = new Relabi({
        waves: [
          { shape: "sine", frequency: 0.75 },
          { shape: "sine", frequency: 1.0 },
          { shape: "sine", frequency: 1.617 },
          { shape: "sine", frequency: 3.141 },
        ],
        bounds: [
          {
            level: -0.75,
            color: "#f33",
            sounds: [
              { instrument: Drums, index: 0 },
              { instrument: Drums, index: 1 },
            ],
          },
          {
            level: 0.75,
            color: "#f83",
            sounds: [
              { instrument: Drums, index: 2 },
              { instrument: Drums, index: 3 },
            ],
          },
          {
            level: -0.25,
            color: "#3b8",
            sounds: [
              { instrument: Kalimba, frequency: 440 },
              { instrument: Kalimba, frequency: (440 * 3) / 2 },
            ],
          },
          {
            level: 0.25,
            color: "#36f",
            sounds: [
              { instrument: Kalimba, frequency: (440 * 6) / 5 },
              { instrument: Kalimba, frequency: (440 * 6) / 7 },
            ],
          },
        ],
      });
      relabiGenerator.start();
      setRelabi(relabiGenerator);
    }
  }, [relabi]);

  useEffect(() => {
    if (relabi && relabiRef.current) {
      relabi.canvas.appendCanvas(relabiRef.current);
    }
  }, [relabi, relabiRef.current]);

  /**
   * Render
   */
  return (
    <div
      style={{
        height: "100%",
        width: "100%",
        padding: 0,
        margin: 0,
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
      }}
    >
      <div ref={relabiRef} />
      <Controls relabi={relabi} />
    </div>
  );
}
