import {API, Auth, Logger} from "@solid/libs";
import {Obj} from "@solid/types";
import {VNPlayer, VNPlayerRecordingStatus, VNPlayerStopCode} from '../VNPlayer';
import {rmdir} from "fs/promises";
import path from "path";

function getCookie(name: string, cookies: string[]): string | undefined {
  for (const cookiePath of cookies) {
    const [cookie/*, path*/] = cookiePath.split("; ");
    const [key, value] = cookie.split("=");
    if (key === name) {
      return value;
    }
  }
  return undefined;
}

const test = async () => {
  const {server, username, password} = {server: "dev1.videonext.net", username: "user", password: "topse"};

  try {
    process.env.API_BACKEND = `https://${server}`;

    const api = new API();
    Auth.setAPI(api);
    await Auth.login({
      username: username,
      password: password
    });
    const setCookie = Auth.api?.lastResponseHeaders ? Auth.api?.lastResponseHeaders["set-cookie"] : [];
    const PHPSESSID = getCookie("PHPSESSID", setCookie);
    api.addHeaders({cookie: `PHPSESSID=${PHPSESSID}`});

    const {list} = await api.getObjectList({
      type: "camera",
      withAttributes: true
    });
    const workList: Obj[] = list.filter((camera: Obj) => camera.attributes.STATUS === "ON" && camera.obj === "b77112fc-2528-11ec-9173-00155dd9270b");
    if (workList.length === 0) {
      throw "Camera list is empty";
    }

    // select first camera from server
    const camera = workList[0];
    const obj: string = camera.obj;

    const base_dir = "g:/solid_data_3";

    //const {url} = await api.getMobileMediaURL({cameraid: obj});
    const urlParameters = {
      cameraid: obj,
      startTime: 20211213143300,
      endTime: 20211213143330,
      isLocal: true
    };

    while (true) {
      try {
        await check(api, urlParameters, base_dir);
        const pathObj = path.join(base_dir, obj);
        console.log("try to remove", pathObj)
        await rmdir(pathObj, {recursive: true});
      }
      catch (e) {
        break;
      }
    }
  }
  catch (e) {
    console.error(e);
  }
};

test();

async function check(api: API, urlParameters: any, base_dir: string): Promise<void> {
  return new Promise(async (resolve, reject) => {
    let {url} = await api.getMobileMediaURL(urlParameters);

    let storer = new VNPlayer(undefined, {
      vsync: false,
      frame_buffers_num: 3,
      logger: new Logger()
    });

    storer.on("state_changed", (state: VNPlayerStopCode, timestamp: number, filename: string, message: string) => {
      if (state == VNPlayerStopCode.EINTERNALERROR) {

      }
    });
    storer.on("recording_status_changed", async (state: VNPlayerRecordingStatus, timestamp: number, filename: string, message: string) => {
      console.log(VNPlayerRecordingStatus[state], new Date(timestamp * 1000), filename, message);

      if (state == VNPlayerRecordingStatus.RECORDING_STARTED) {
        console.log("Request archive from {{storage}} to offline archive");
      } else
      if (state == VNPlayerRecordingStatus.RECORDING_ERROR) {
        console.error(filename, message);
        reject();
      } else
      if ((state == VNPlayerRecordingStatus.RECORDING_ENDED
           || state == VNPlayerRecordingStatus.RECORDING_SKIPPED)
      ) {
        resolve();
      }
    });
    await storer.store(urlParameters.cameraid, url, base_dir);
  });
}
