// Modul na komand "anketa"

import { ActionRowBuilder, APIEmbed, ButtonBuilder, ButtonStyle, Message, MessageComponentInteraction } from "discord.js";
import { emouty } from "../utils/emotes";
import { Modul } from "../utils/types";
import { formatter } from "../utils/utils";

const exp: Modul = {
  more_komandy: {

    anketa: {
      arg: "nastavení asi IDK",
      run: async (mes, arg) => {
        const args = arg.toLocaleLowerCase().split(" ");

        const settings = {
          time: 60,
          immediateShow: true
        };

        switch (args[0]) {
          case "custom":
          case "vlastni":
            return `tuto jeste neni implemenovany ${emouty.sjeta}`;

          case "start":
          case "zapnout": {
            const temp = args.slice(1).join(" ");
            const moznosti = temp.split(temp.indexOf("|") > -1 ? "|" : ",").reduce<string[]>((acc, c) => {
              if (c.length) acc.push(c.trim());
              return acc;
            }, []);
            if (moznosti.length < 2) return "zadej alespo%n dve moznosti";

            const konec = new Date();
            konec.setSeconds(konec.getSeconds() + settings.time);

            const embed: APIEmbed = {
              title: "Hlasování",
              description: settings.immediateShow ? `Končí ${formatter(konec)}` : `Výsledky se zobrazí ${formatter(konec)}`,
              fields: []
            };
            const radek = new ActionRowBuilder<ButtonBuilder>();
            const odpovedi: Record<string, number> = {};

            function prepocitat(): void;
            function prepocitat(int: MessageComponentInteraction): void;
            function prepocitat(int?: MessageComponentInteraction) {
              const celkem = Object.keys(odpovedi).length;
              embed.fields?.forEach((f, i) => {
                const hovn = Object.values(odpovedi).filter(n => n == i);
                const dylka = hovn.length;
                const p = Math.floor(dylka / celkem * 10) || 0;
                f.value = `${"█".repeat(p)}${"░".repeat(10 - p)} ${Math.round(dylka / celkem * 100) || 0}% (${dylka})`;
              });
              int?.update({ embeds: [embed] });
            }

            moznosti.forEach((h, i) => {
              if (settings.immediateShow) embed.fields?.push({ name: h, value: "" });
              radek.addComponents(new ButtonBuilder({ customId: `${i}`, label: h, style: ButtonStyle.Primary }));
            });
            prepocitat();
            const zprava = await mes.channel.send({ embeds: [embed], components: [radek] });
            const collector = mes.channel.createMessageComponentCollector({ filter: i => i.message.id == zprava.id, time: settings.time * 1000 });

            collector.on("collect", d => {
              if (!(d.message instanceof Message)) return;
              const i = Number(d.customId);
              const prev = odpovedi[d.user.id];
              if (prev == i) return void d.deferUpdate();
              odpovedi[d.user.id] = i;
              if (!settings.immediateShow) return void d.deferUpdate();
              prepocitat(d);
            });

            collector.on("end", () => {
              embed.description = `Skončilo ${formatter(konec)}`;
              if (!settings.immediateShow) prepocitat();
              zprava.edit({ components: [], embeds: [embed] });
            });
            break;
          }

          default:
            return `takovi to "${args[0]}" sem moc nepochitil`;
        }
      }
    }
  }
};

module.exports = exp;
