import m, {Component} from "mithril";
import {__, API, Auth, Logger} from "@solid/libs";
import {MSEMediaPlayerConnection, Obj} from "@solid/types";
import {YUVPlayer} from "@libs/player-native";

import "@solid/player/mediaplayer.css";
import "@solid/player/mediaplayercontrols.css";
import "@libs/player-native/yuvplayer.css";
import "./style.css";

declare global {
  interface Window {
    started: boolean,
    [key: string]: any;
  }
}

async function checkLogin() {
  try {
    const api = new API();
    await api.getInfo();
  }
  catch ({code, message}) {
    if (code === 403 || code === 401) {
      const api = new API();
      Auth.setAPI(api);
      try {
        await Auth.login({
          username: process.env.API_USER ?? "",
          password: process.env.API_PASS ?? ""
        });
      }
      catch (e) {
        console.error("Cannot login", e);
        throw e;
      }
    }
  }
}

async function start() {
  console.log("start");
  await checkLogin();

  const root = document.querySelector("#root");
  if (!root) {
    return;
  }

  const api = new API();
  const list: Obj[] = [];
  const response = await api.getObjectList({type: "camera", withAttributes: true});
  for (const row of response.list) {
    if (row.attributes.STATUS === "ON") {
      list.push(row);
    }
  }

  type CellAttrs = {
    camera: Obj
  };
  const Cell = (): Component<CellAttrs> => {
    let player: YUVPlayer;
    let storer: YUVPlayer;

    return {
      oncreate: ({attrs, dom}) => {
        const node = dom.querySelector(".player") as HTMLDivElement | null;
        if (!node) {
          return;
        }
        const logger = new Logger();
        player = new YUVPlayer({node: node, logger: logger});
        storer = new YUVPlayer({ logger: new Logger({doubleToConsole: true}) });
        const init = async () => {
          if (!player || !storer) {
            return;
          }

          await player.init({
            showPauseButton: true
          });
          await storer.init({jitter_buffer_len: 0});
          storer.setPreferredConnectionType(MSEMediaPlayerConnection.CLOUD, false);
        };
        init();
      },
      onremove: () => {
        player.destroy();
        storer.destroy();
      },
      view: ({attrs}) => {
        return m(".cell", [
          `[${attrs.camera.obj}] ${attrs.camera.name}`,
          m("button.play", {
            onclick: () => {
              player.stop();
              player.play(attrs.camera.obj);
            }
          }, "Play"),
          m("button.stop", {
            onclick: () => {
              player.stop();
            }
          }, "Stop"),
          m(".player")
        ]);
      }
    };
  };

  // clean, page can be updated by hmr
  m.mount(root, null);

  let isShow = true;
  m.mount(root, {
    view: () => {
      return m("div", [
        m("controls", [
          m("button.showHide", {
            onclick: () => {isShow = !isShow;}
          }, isShow ? "Hide" : "Show")
        ]),
        isShow && list.map((row) => {
          return m(Cell, {camera: row});
        })
      ]);
    }
  });
}

if (window.started) {
  start();
}

window.onload = () => {
  window.started = true;
  start();
};


