import { Client, TextChannel } from "discord.js";
import fetch from "node-fetch";
import { emouty } from "../utils/emotes";
import { Modul } from "../utils/types";
import { log } from "../utils/utils";

let posledniDatum = "";
let client: Client;

function naplanovat(): void;
function naplanovat(jesteNeska: true): void;
function naplanovat(jesteNeska?: true) {
  const novyCas = new Date();
  const den = novyCas.getDay();

  if (jesteNeska && den == 4) return hendelieren();

  novyCas.setDate(novyCas.getDate() + ((den < 4 ? 4 : 11) - den));
  novyCas.setHours(15);
  novyCas.setMinutes(0);
  setTimeout(hendelieren, Number(novyCas) - Number(new Date()));
}

const padNula = (n: number) => n > 9 ? n : `0${n}`;

function hendelieren() {
  const base = "https://sktorrent.eu/torrent/";
  fetch(`${base}torrents_v2.php?search=ordinace`)
    .then(r => r.text())
    .then(txt => {
      const tabule = txt.match(/<table width="100%" class="lista">(?<kontent>.+)<\/table>/is);
      if (!tabule) return log(new Error("nenašel jsem tabuleho"));

      const detaily = tabule.groups!.kontent.match(/<a href="d.+?&(?<odkaz>id=.+?)".+?Pridany (?<datum>\d\d\/\d\d\/\d{4})/is);
      const datum = detaily!.groups!.datum;

      if (posledniDatum == "") {
        const d = new Date();
        if (`${padNula(d.getDate())}/${padNula(d.getMonth() + 1)}/${d.getFullYear()}` == datum) {
          return naplanovat();
        }

        posledniDatum = datum;
        return setTimeout(hendelieren, 18e4);
      }

      if (posledniDatum == datum) return setTimeout(hendelieren, 18e4);

      (client.channels.cache.get("555779161067749448") as TextChannel).send(`<@&591306633196339261> vyšla nová vordinačka ${emouty.lajk}\n${base}download.php?${detaily?.groups?.odkaz}`);
      naplanovat();
      return;
    });
}

const exp: Modul = {

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

    naplanovat(true);
  }
};

module.exports = exp;
