// Komandy nebo handelery který se nikam jinam nehodí

import { getVoiceConnections } from "@discordjs/voice";
import { Client, Message, User } from "discord.js";
import { emouty } from "../utils/emotes";
import { createServer } from "http";
import { Modul } from "../utils/types";
import fetch from "node-fetch";
import { formatCas, log } from "../utils/utils";

let spim = false;

const exp: Modul = {
  more_komandy: {

    debug_log: {
      hidden: true,
      run: (_, arg) => {
        log("log:", arg);
        return "je to v konzoli";
      }
    },

    update: {
      als: ["apdejt"],
      run: async mes => {
        const sudo = mes.channel.id == process.env.adminChannel || mes.author.id == process.env.adminID;
        if (!sudo) {
          const verze = await fetch("https://denim3001.deadfish.cz/version.txt")
            .then(r => r.text());
          if (verze == require("../../package.json").version) return `ale ja se nemam co priucit vole kkte ${mes.author}`;
        }

        getVoiceConnections().forEach(con => con.disconnect());
        const client: Client = module.exports.client;
        client.user?.setStatus("invisible");
        mes.react("👋")
          .then(() => process.exit());
      }
    },

    lastuptime: () => {
      const cislo = Number(process.argv[2]);
      if (!cislo) return "aj forgor 💀";
      return `naposled jsem jel ${formatCas(cislo)}`;
    }
  },

  super_on_messageCreate: {
    pos: 0,
    fun: (mes: Message) => {
      const cont = mes.content.toLowerCase();
      const prefix = process.env.prefix || "more";
      if (cont == `${prefix} zapni se`) {
        if (spim) {
          spim = false;
          mes.client.user?.setStatus("online");
          mes.channel.send("dobré ráno magoří");
        }
        else mes.channel.send("tak jsi kokot?");
      } else if (!spim) {
        if (cont == `${prefix} vypni se`) {
          mes.react(emouty.purfieRIP);
          getVoiceConnections().forEach(con => con.disconnect());
          mes.client.user?.setStatus("invisible");
          spim = true;
        }
        else return false;
      }
      return true;
    }
  },

  on_ready: () => {
    createServer((req, res) => {
      res.statusCode = 400;
      if (req.socket.remoteAddress != "::1") return res.end("di doprdele dyk ne more");

      const sp = new URL(req.url!, `http://${req.headers.host}`).searchParams;
      const { userID, content } = Object.fromEntries(sp.entries());
      if (!userID || !content) return res.end("gde mas userID a content????");

      const client: Client = module.exports.client;
      const user = client.users.cache.get(userID);
      if (!user) return res.end("takovyho kkta neznam");

      user.createDM().then(async dm => {
        await dm.send(content);
        res.statusCode = 200;
        res.end("OK");
      }).catch((e: Error) => {
        if (e.message.search("2000 or fewer")) return res.end("content je moc dlouhej");
        log("error pri posilani upozorneni", e);
        res.statusCode = 500;
        res.end("neco se posralo");
      });
    }).listen(1298);
  },

  on_userUpdate: (bef: User, aft: User) => {
    if (bef.avatar == aft.avatar) return;

    aft.createDM().then(ch => {
      ch.send("cus bracho vydim ze sis zmenim profilofku na dalsi mrdku estli chces abi se ukazovala na na v3ech sr4kach kterz sou na dedfis.cy tak se tam prosymte prihlas haby se mohla zmnenit syk");
    });
  }
};

module.exports = exp;
