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

function getCookie(name: string, cookies: string[]) {
  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;

        console.log(obj);

        const {url} = await api.getMobileMediaURL({cameraid: obj}); //, startTime: "20211130122300", endTime: 20211130122330});

        console.log(url);

        let player = new VNPlayer(undefined, {vsync: false, frame_buffers_num: 3, log_level: 'debug'});
        await player.play(obj, url, 1.0);

        await Utils.wait(10000);

        // testing pause
        player.pause();

        await Utils.wait(5000);

        // resume in forward direction
        player.resume(1);

        await Utils.wait(15000);

        // finally stop
        player.teardown();
    }
    catch (e) {
        console.error(e);
    }
};

test();
