import { GuildScheduledEventEntityType, GuildScheduledEventPrivacyLevel, TextChannel } from "discord.js";
import { CClient, Modul } from "../utils/types";
import { log } from "../utils/utils";

let client: CClient;

async function ziskatNazev() {
	const stranka = await fetch("https://voyo.nova.cz/api/v1/show/content?showId=1&type=episodes&season=6596&count=1&offset=0&url=%2Fserialy%2F1-ordinace-v-ruzove-zahrade-2")
		.then(r => r.text())
		.catch(e => log("chyba pri accessovani VOYO stránky", e));

	const nazevFull = /h3 class=\"title\">.+?>(.+?)<\//s.exec(stranka || "");

	if (!nazevFull) {
		log(new Error("neni nazev"));
		return "Vordinačka";
	}

	const nazevCasti = /(?<cislo>\d+). díl - (?<nazev>.+)/.exec(nazevFull[1]);

	return nazevCasti ? `${nazevCasti.groups!.cislo}. ${nazevCasti.groups!.nazev}` : nazevFull[1];
}

async function naplanovat() {
	const datum = new Date();
	const den = datum.getDay();

	if (!(den == 1 && datum.getHours() < 12))
		datum.setDate(datum.getDate() + ((den == 0 ? 1 : 8) - den));

	datum.setHours(13);
	datum.setMinutes(0);
	datum.setSeconds(0);

	setTimeout(urobit, Number(datum) - Number(new Date()));
}

async function urobit() {
	const guilda = client.guilds.cache.get("555779161067749446");

	if (!guilda) return log(new Error("dobytcarna nenalezena"));

	const kdyToBude = new Date();
	kdyToBude.setHours(20);
	kdyToBude.setSeconds(0);

	const event = await guilda.scheduledEvents.create({
		name: await ziskatNazev(),
		scheduledStartTime: kdyToBude,
		entityType: GuildScheduledEventEntityType.Voice,
		privacyLevel: GuildScheduledEventPrivacyLevel.GuildOnly,
		channel: "891067481651839037"
	});

	const general = guilda.channels.cache.get("555779161067749448") as TextChannel;

	if (!general) return log(new Error("general nenalezen"));

	general.send(`<@&1123186280843444274> ${event.url}`);

	naplanovat();
}

const exp: Modul = {
	more_komandy: {
		dalsiordinacka: () => `dalsi ordnacka <t:${Math.ceil((Date.now() - 414000000) / 604800000) * 604800 + 414000}:R>`
	},

	on_ready: () => {
		client = module.exports.client;

		naplanovat();
	}
};

module.exports = exp;
