import {Obj} from "@solid/types";
import {spawn} from "child_process";
import {API, Auth} from "@solid/libs";

// code page on windows can be differ from utf-8, then run "chcp 65001" in cmd before calling this scripts

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 server = "dev1.videonext.net";
const username = "user";
const password = "topse";

const run = async () => {
	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 = camera.obj;

		const {url} = await api.getMobileMediaURL({cameraid: obj});

		const args = ["-d", "-u", url];

		const command = spawn("simple_play", args, {shell: true});
		command.stdout.on("data", data => {
			console.log(`stdout: ${data}`);
		});

		command.stderr.on("data", data => {
			console.log(`stderr: ${data}`);
		});

		command.on('error', (error) => {
			console.log(`error: ${error.message}`);
		});

		command.on("close", code => {
			console.log(`child process exited with code ${code}`);
		});
	}
	catch (e) {
		console.error(e);
	}
};

run();
