// Cokoliv co má něco společnýho s vojsem

import { getVoiceConnection } from "@discordjs/voice";
import { ChannelType, GuildMember, Message, VoiceChannel } from "discord.js";
import { emouty } from "../utils/emotes";
import { CClient, Modul } from "../utils/types";
import { log, rand } from "../utils/utils";
import { handlePrevVoice, Hratelny, novejJoin, novejLeave, novejPlay, Priority } from "../utils/voice";

const muty: string[] = [];
let neodposlouchavani = false;

const vytahnout = (member: GuildMember, patro: number) => {
  const vojs = member.voice.channel;
  if (!vojs) return;

  const aktPatro = Number(vojs.name) || 0;
  let dalsiPatro: number | string = aktPatro;
  if (patro < aktPatro) dalsiPatro--; else if (patro > aktPatro) dalsiPatro++; else return;
  if (dalsiPatro === 0) dalsiPatro = "P";

  const dalsiVojs = member.guild.channels.cache.filter(channel => channel.type == ChannelType.GuildVoice && channel.name === String(dalsiPatro)).first() as VoiceChannel | undefined;
  if (!dalsiVojs) return;

  member.voice.setChannel(dalsiVojs);
  setTimeout(() => vytahnout(member, patro), 1e3);
};

async function playAndFukOff(mes: Message, jinak: string, zvuk: string | Hratelny[]) {
  const channel = mes.member?.voice.channel;
  if (!channel) return jinak;

  const prev = await novejJoin(mes.guild!, channel.id);

  await novejPlay(mes.guildId!, zvuk, Priority.Etc)
    .catch(e => {
      log("Pičo chyba při fukofování", e);
    });

  handlePrevVoice(prev, mes.guild!);
}

const exp: Modul = {
  more_komandy: {

    wojs: mes => `vojs se pise s normalnim v ti kriple ${mes.author}`,

    vojs: {
      arg: "potichu (nepovinné)",
      DMUnsafe: true,
      run: (mes, arg) => {
        const channel = mes.member?.voice.channel;
        if (!channel) return `di si tam sam ne ty gadzo ${mes.author}`;

        const nahlas = !arg.startsWith("potichu");

        novejJoin(mes.guild!, channel.id)
          .then(prev => {
            if (prev != true && nahlas) novejPlay(mes.guildId!, "zvuky/nazdar.ogg", Priority.Etc);
          });

        if (nahlas) return "<@&591306633196339261> vojs";
      }
    },

    vypadni: {
      als: ["odejdi", "disconnect", "leave", "odpoj", "votpoj", "vodpoj", "vodprejskni", "tahni"],
      DMUnsafe: true,
      run: mes => {
        const userChannel = mes.member?.voice.channel;
        const jsemTam = userChannel?.members.has(mes.client.user!.id);

        if (!novejLeave(mes.guildId!)) return "nejsem ve vojsu";

        if (jsemTam) {
          mes.member?.voice.disconnect();
          mes.react(emouty.fu);
        } else {
          mes.react(emouty.purfieRIP);
        }
      }
    },

    vytah: {
      als: ["vitah"],
      DMUnsafe: true,
      run: (mes, parto) => {
        if (!mes.member?.voice.channel) return `nejsi ve vojsu ty gadzo ${mes.author}`;
        if (!parto) return `napis do jakiho patra ${mes.author}`;

        vytahnout(mes.member, Number(parto) || 0);
      }
    },

    krkacek: {
      als: ["krk", "grg", "grgnisi", "krknisi", "grgacek"],
      run: mes =>
        playAndFukOff(mes, "***grrrrrrrrg***", "zvuky/grg.mp3")

    },

    cas: {
      cd: 5,
      run: async mes => {
        const date = new Date();
        const h = date.getHours();
        const m = date.getMinutes();
        const pre = "zvuky/cas/";

        const addSuffix = (prefix: string, hodnota: number) => {
          const koncovka = hodnota == 1 ? "a" : hodnota > 1 && hodnota < 5 ? "y" : "";
          return `${prefix}${koncovka}`;
        };
        const rozdelAPridej = (cislo: number) => {
          if (cislo == 2) return zvuky.push({ src: `${pre}dvě.mp3`, volume: 2.5 });
          if (cislo < 20) return zvuky.push({ src: `${pre}${cislo}.mp3`, volume: 2.5 });
          const text = String(cislo);
          zvuky.push({ src: `${pre}${text[0]}0.mp3`, volume: 2.5 });
          if (text[1] != "0") zvuky.push({ src: `${pre}${text[1]}.mp3`, volume: 2.5 });
        };

        const hod = addSuffix("hodin", h);
        const min = addSuffix("minut", m);
        const je = h > 1 && h < 5 ? "jsou" : "je";

        const zvuky: Hratelny[] = [{ src: `${pre}${je}.mp3`, volume: 2.5 }];

        rozdelAPridej(h);
        zvuky.push({ src: `${pre}${hod}.mp3`, volume: 2.5 });
        if (m > 0) {
          rozdelAPridej(m);
          zvuky.push({ src: `${pre}${min}.mp3`, volume: 2.5 });
        }

        return playAndFukOff(mes, `${je} ${h} ${hod} ${m} ${min}`, zvuky);
      }
    },

    outro: {
      hidden: true,
      run: mes =>
        playAndFukOff(mes, "co to znamena ti gadzovko", "zvuky/pocasi/outro.mp3")

    },

    auto: mes =>
      playAndFukOff(mes, "vžum", "zvuky/auto.ogg"),

    reknivtip: mes => {
      const zvuk = ["a_jednou_sel_a_tak_moc_sel", "a_sedel", "a_sel_z_vaku_a_vykopal_marese", "a_si_rekl", "a_si_vsimnul", "u_zamestnaly_na_praxi"][rand(7)];
      const client: CClient = module.exports.client;
      return playAndFukOff(mes, (client.komandy["vtip"].run as (() => string))(), `zvuky/ftipy/toz_sims${zvuk}.mp3`);
    },

    zmenneodposlouchavani: () => {
      neodposlouchavani = !neodposlouchavani;
      return `Funkce NEOTPOSLOUCHAAVEJJJ!!§!§ je ${neodposlouchavani ? "nastartovana" : "chcipnuta"}`;
    }

  },

  // Neodposlouchávej
  on_voiceStateUpdate: (bef, aft) => {
    const conn = getVoiceConnection(aft.guild.id);
    if (!aft.channel || !conn || aft.member?.user.id == aft.client.user?.id) return;

    if (neodposlouchavani && aft.selfMute && !aft.deaf) {
      novejPlay(aft.channel.guildId, { src: "./zvuky/neodposlouchavej.ogg", volume: 0.38 }, Priority.Etc)
        .then(() => {
          if (!aft.selfMute) return;
          aft.setDeaf(true, "otposlouchávala ta gadza");
          if (!muty.includes(aft.member!.id)) muty.push(aft.member!.id);
        })
        .catch(e => {
          log("chyb při neodposlouchavej", e);
        });
    }

    if (!bef.channel) return;
    if (bef.mute && bef.deaf && !aft.mute && aft.serverDeaf && muty.includes(aft.member!.id)) {
      aft.setDeaf(false, "us muze poslouchat gadza");
      muty.splice(muty.indexOf(aft.member!.id), 1);
    }
  }
};

module.exports = exp;
