import {Checkws} from "@libs/player-native/test/checkws";
import {API, Auth, ptsToTimestamp} from "@solid/libs";

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;
}

async function start() {
  const api = new API();
  const check = new Checkws(api);

  const {server, username, password} = {server: "dev1.videonext.net", username: "user", password: "topse"};
  process.env.API_BACKEND = `https://${server}`;

  const startTime = ptsToTimestamp(20211213143300);
  const endTime = ptsToTimestamp(20211213143330);
  console.log(startTime, endTime);
  try {
    process.env.API_BACKEND = `https://${server}`;

    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}`});

    // console.log("--- CHECK Cloud ---");
    // await check.check("b77112fc-2528-11ec-9173-00155dd9270b", startTime, endTime, false);

    console.log("--- CHECK Local ---");
    let i = 0;
    let success = 0;
    while (true) {
      try {
        console.log(`--> ${i} <--`);
        await check.check("b77112fc-2528-11ec-9173-00155dd9270b", startTime, endTime, true);
        success++;
      }
      catch (e) {
        break;
      }
      i++
    }
    console.log("success", success);
  }
  catch (e) {
    console.error(e);
  }
}

start();
