import prompts from 'prompts';
import {API, Auth} 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.split("=");
		if (key === name) {
			return value;
		}
	}
	return undefined;
}

const rec = 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);

        let {url} = await api.getMobileMediaURL({cameraid: obj, startTime: "20211127095000", endTime: "20211127095059"});
        console.log(url);

        const base_dir = "/tmp/vasm";

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

        /**
        *
        * @param {number} time ms
        * @returns {Promise<number>}
        */
        const sleep = (time: number) => new Promise((resolve) => setTimeout(resolve, time));

        await sleep(60000);

        await player.play_local(obj, 1638006600, 1638006659, 1, base_dir);

        await sleep(60000);

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

rec();
