import prompts from 'prompts';
import {API, Auth, ptsToTimestamp} from "@solid/libs";
import {Obj} from "@solid/types";
import {VNPlayer} from '../VNPlayer';

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

const test = async () => {
    const {server, username, password} = await prompts([{
        type: "text",
        name: 'server',
        message: 'server url (ex: dev1.videonext.net)',
        initial: 'dev1.videonext.net'
    },{
        type: "text",
        name: 'username',
        message: 'username',
        initial: 'user'
    },{
        type: "text",
        name: 'password',
        message: 'password',
        initial: '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 = list.filter((camera: Obj) => camera.attributes.STATUS === "ON");
        if (workList.length === 0) {
            throw "Camera list is empty";
        }

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

        let player = new VNPlayer(undefined, {
          vsync: false,
          frame_buffers_num: 3,
          log_level: 'debug'
        });

      let i = 0;
        while (true) {
          console.log(`---> ${i} <---`);
          const endTime = 20211207224430;
          const {url} = await api.getMobileMediaURL({
            cameraid: obj,
            startTime: 20211207214400,
            endTime: endTime
          });

          await player.play(obj, url, 30.0);

          await newFrame(player, ptsToTimestamp(endTime));

          player.teardown();
          i++;
        }
    }
    catch (e) {
        console.error(e);
    }
};

function newFrame(player: VNPlayer, endTime: number): Promise<void> {
  return new Promise((resolve) => {
    player.on("new_frame", (frameInfo) => {
      if (frameInfo.ts / 1000 > endTime) {
        resolve();
      }
    });
  })
}

test();
