const { ButtonBuilder } = require('discord.js');

module.exports = {
  name: "xox",
  description: "XOX oynamanÄ±za yarar.",
  usage: "xox @KullanÄ±cÄ±",
  aliases: [],
  category: "Games",
  memberPermissions: [],
  botPermissions: ["SendMessages", "EmbedLinks"],
  nsfw: false,
  cooldown: 5000,
  ownerOnly: false,

  async execute(client, message, args, data) {

    this.verifyWin = (sides) => {
      return (sides[0] === sides[1] && sides[0] === sides[2])
        || (sides[0] === sides[3] && sides[0] === sides[6])
        || (sides[3] === sides[4] && sides[3] === sides[5])
        || (sides[1] === sides[4] && sides[1] === sides[7])
        || (sides[6] === sides[7] && sides[6] === sides[8])
        || (sides[2] === sides[5] && sides[2] === sides[8])
        || (sides[0] === sides[4] && sides[0] === sides[8])
        || (sides[2] === sides[4] && sides[2] === sides[6]);
    };

    const opponent = message.mentions.users.first();

    if (!opponent)
      return message.channel.send({
        embeds: [
          {
            color: client.settings.embedColors.red,
            title: '**Â»** Oynamak Ä°stediÄŸin KiÅŸiyi Etiketlemelisin!',
            description: `**â€¢** Ã–rnek kullanÄ±m: \`${data.prefix}xox @RFKaya\``
          }
        ]
      });

    if (opponent.bot)
      return message.channel.send({
        embeds: [
          {
            color: client.settings.embedColors.red,
            title: '**Â»** Botlarla OynayamazsÄ±n!',
            description: `**â€¢** Botlar savunmasÄ±zdÄ±r, onlara ÅŸiddet uygulama.`
          }
        ]
      });

    if (opponent.id == client.user.id)
      return message.channel.send({
        embeds: [
          {
            color: client.settings.embedColors.red,
            title: '**Â»** Benimle OynayamazsÄ±n!',
            description: `**â€¢** Ã‡Ã¼nkÃ¼ henÃ¼z benim seviyemde deÄŸilsin ğŸ˜�`
          }
        ]
      });

    if (opponent.id === message.author.id)
      return message.channel.send({
        embeds: [
          {
            color: client.settings.embedColors.red,
            title: '**Â»** N-Ne? Kendinle mi savaÅŸacaksÄ±n? O nasÄ±l oluyormuÅŸ?',
            description: `**â€¢** Kendine zarar verme canÄ±m. HayatÄ±ndaki en deÄŸerli kiÅŸi kendinsin ğŸ˜š`
          }
        ]
      });

    if (client.gamesPlaying.has(message.channel.id))
      return message.channel.send({
        embeds: [
          {
            color: client.settings.embedColors.red,
            title: '**Â»** Bu Kanalda Devam Eden Bir YarÄ±ÅŸma Bulunuyor!',
            description: `**â€¢** YarÄ±ÅŸmalarÄ±nÄ±n bitmesini bekleyebilir veya farklÄ± kanalda deneyebilirsin.`
          }
        ]
      });


    client.gamesPlaying.set(message.channel.id, this.name);

    const { buttonConfirmation } = require("../../modules/Functions");
    const buttonConfirmationResult = await buttonConfirmation(
      message,
      [
        {
          color: client.settings.embedColors.default,
          title: `**Â»** ${opponent.username}, XOX isteÄŸini kabul ediyor musun?`,
          description: `**â€¢** ButonlarÄ± kullanarak cevaplayabilirsin.`
        }
      ],
      opponent.id
    );
    if (!buttonConfirmationResult.status) {

      client.gamesPlaying.delete(message.channel.id);

      return buttonConfirmationResult.reply.edit({
        embeds: [
          {
            color: client.settings.embedColors.red,
            title: '**Â»** Meydan Okuma Kabul Edilmedi!',
            description: `**â€¢** ÃœzgÃ¼nÃ¼m, istersen [destek sunucumuza](https://discord.gg/VppTU9h) katÄ±lÄ±p orada birilerini bulabilirsin.`
          }
        ],
        components: []
      }).catch(() => { });

    }

    buttonConfirmationResult.reply.edit({
      embeds: [
        {
          color: client.settings.embedColors.green,
          description: `**Â»** Meydan okuma kabul edildi!`
        }
      ],
      components: []
    });

    try {

      const sides = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
      const taken = [];
      let userTurn = true;
      let winner = null;
      let drawStatus = false;
      let toplamSÄ±raAtlama = 0;
      while (!winner && !drawStatus && taken.length < 9) {
        const user = userTurn ? message.author : opponent;
        const sign = userTurn ? 'X' : 'O';
        await message.channel.send(
          `${user}, hangi tarafÄ± almak istersin?\n` +
          `\`\`\`\n` +
          `${sides[0]} | ${sides[1]} | ${sides[2]}\n` +
          `â€”â€”â€”â€”â€”â€”â€”â€”â€”\n` +
          `${sides[3]} | ${sides[4]} | ${sides[5]}\n` +
          `â€”â€”â€”â€”â€”â€”â€”â€”â€”\n` +
          `${sides[6]} | ${sides[7]} | ${sides[8]}\n` +
          `\`\`\``);
        const filter = res => {
          const choice = res.content;
          return res.author.id === user.id && sides.includes(choice) && !taken.includes(choice);
        };
        const turn = await message.channel.awaitMessages({ filter, max: 1, time: 15000 });
        if (!turn.size) {
          toplamSÄ±raAtlama += 1;

          await message.channel.send({
            embeds: [
              {
                color: client.settings.embedColors.red,
                title: '**Â»** SÃ¼ren Doldu!',
                description: `**â€¢** SÄ±ran rakibine geÃ§ti.`
              }
            ]
          });

          if (toplamSÄ±raAtlama >= 4) {
            drawStatus = true;
            break;
          }

          userTurn = !userTurn;
          continue;
        }
        const choice = turn.first().content;
        sides[Number.parseInt(choice, 10)] = sign;
        taken.push(choice);
        if (this.verifyWin(sides)) winner = userTurn ? message.author : opponent;
        userTurn = !userTurn;
      }

      client.gamesPlaying.delete(message.channel.id);

      return message.channel.send({
        embeds: [
          (winner
            ? {
              color: client.settings.embedColors.green,
              title: `**Â»** Tebrikler ${winner.username}, kazandÄ±n! ğŸ�†`
            }
            : {
              color: client.settings.embedColors.red,
              title: `**Â»** Maalesef, kimse kazanamadÄ±.`
            }
          )
        ]
      });

    } catch (err) {
      client.gamesPlaying.delete(message.channel.id);
      throw err;
    }
  }
};