const { ApplicationCommandOptionType, EmbedBuilder,ActionRowBuilder,StringSelectMenuBuilder,PermissionsBitField,ActivityType, AttachmentBuilder} = require("discord.js");
const axios = require('axios');
const cezapuan = require("../../../../../../Global/Schemas/cezapuan")
const moment = require("moment");
const levels = require("../../../../../../Global/Schemas/level");
const { profileImage } = require('discord-arts');
const kanal = require("../../../../../../Global/Settings/AyarName");
const Coin = require("../../../../../../Global/Schemas/ekonomi");
const ertuSpotify  = require("../../../../../../Global/Plugins/Spotify/Spotify");

require("moment-duration-format")
moment.locale("tr")
module.exports = {
    name: "profil",
    description: "KullanÄ±cÄ±nÄ±n discord verilerini gÃ¶sterir.",
    category: "USER",
    cooldown: 0,
    command: {
      enabled: true,
      aliases: ["me","kb","info","bilgi","kullanÄ±cÄ±bilgi"],
      usage: ".profil",
    },

    onLoad: function (client) { },

    onCommand: async function (client, message, args, ertuembed) {

    let kanallar = kanal.KomutKullanÄ±mKanalÄ°sim;
    if (!message.member.permissions.has(PermissionsBitField.Flags.Administrator) && !kanallar.includes(message.channel.name)) return message.reply({ content: `${kanallar.map(x => `${client.channels.cache.find(chan => chan.name == x)}`)} kanallarÄ±nda kullanabilirsiniz.` }).then((e) => setTimeout(() => { e.delete(); }, 10000));

    let Ã¼ye = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member;
    if (Ã¼ye.user.bot) return;

    const row = new ActionRowBuilder()
      .addComponents(
        new StringSelectMenuBuilder()
          .setCustomId('profil')
          .setPlaceholder(`${Ã¼ye.user.username} isimli kullanÄ±cÄ±nÄ±n detaylarÄ±nÄ± gÃ¶rÃ¼ntÃ¼le!`)
          .addOptions([
            { label: "Genel Ä°statistikler", description: `${Ã¼ye.user.username} Ã¼yesinin sunucu iÃ§erisinde aktifliÄŸini gÃ¶sterir.`, emoji: { id: "948674910425853993" }, value: "stat" },
            { label: "Ceza GeÃ§miÅŸi", description: `${Ã¼ye.user.username} Ã¼yesinin ceza geÃ§miÅŸini listelenir.`, emoji: { id: "948677924561752104" }, value: "cezalarim" },
            { label: "Ses GeÃ§miÅŸi", description: `${Ã¼ye.user.username} Ã¼yesinin ses kayÄ±tlarÄ±nÄ± gÃ¶sterir.`, emoji: { id: "948679866562277456" }, value: "sesgecmisim" },
            { label: "Ekonomi Durumu", description: `${Ã¼ye.user.username} Ã¼yesinin ekonomi durumunu gÃ¶sterir.`, emoji: { id: "948674949567111248" }, value: "coin" },
            { label: 'Profil FotoÄŸrafÄ±', description: `${Ã¼ye.user.username} Ã¼yesinin profil resmini bÃ¼yÃ¼tÃ¼r.`, emoji: { id: '926954863647150140' }, value: 'avatar' },
            { label: 'Profil KapaÄŸÄ±', description: `${Ã¼ye.user.username} Ã¼yesinin profil arkaplanÄ±nÄ± bÃ¼yÃ¼tÃ¼r.`, emoji: { id: '926954863647150140' }, value: 'banner' },
          ]),
      );

    let platform = { web: '`Ä°nternet TarayÄ±cÄ±sÄ±` `ðŸŒ�`', desktop: '`PC (App)` `ðŸ’»`', mobile: '`Mobil` `ðŸ“±`' }
    if(Ã¼ye.presence && Ã¼ye.presence.status !== 'offline') { bilgi = `\` â€¢ \` BaÄŸlandÄ±ÄŸÄ± Cihaz: ${platform[Object.keys(Ã¼ye.presence.clientStatus)[0]]}` } else { bilgi = '\` â€¢ \` BaÄŸlandÄ±ÄŸÄ± Cihaz: `Ã‡evrimdÄ±ÅŸÄ±` `ðŸ”»`' }
    let cezapuanData = await cezapuan.findOne({ userID: Ã¼ye.user.id });
    let coindb = await Coin.findOne({ userID: Ã¼ye.user.id })
    if(!coindb) coindb = await Coin.findOneAndUpdate({guildID:message.guild.id,userID:Ã¼ye.user.id},{$set:{coin:1000,beklemeSuresi:Date.now(),gameSize:0,profilOlusturma:Date.now(),hakkimda:"Girilmedi",evlilik:false,evlendigi:undefined,dailyCoinDate:(Date.now() - 86400000)}},{upsert:true, new:true})
    let yuzukisim;
    switch (coindb ? coindb.evliolduguyuzuk : "Evli DeÄŸil") {
      case "pirlanta":
        yuzukisim = "PÄ±rlanta";
        break;
      case "baget":
        yuzukisim = "Baget";
        break;
      case "tektas":
        yuzukisim = "TektaÅŸ";
        break;
      case "tria":
        yuzukisim = "Tria";
        break;
      case "bestas":
        yuzukisim = "BeÅŸtaÅŸ";
        break;
      default:
        yuzukisim = "Evli DeÄŸil"
    }
    let member = message.guild.members.cache.get(Ã¼ye.id)
const roles = member.roles.cache.filter(role => role.name !== "@everyone").array().map(role => "<@&" + role.id + ">");
const roleList = member.roles.cache.size <= 5
  ? roles.join(", ")
  : "Listelenemedi!";
    const evlendigitarih = coindb ? coindb.evlendigitarih : null;
    const evlendigiTarihi = evlendigitarih ? `<t:${Math.floor(evlendigitarih / 1000)}:R>` : "\`Evli DeÄŸil\`";

    message.react(`${client.emoji("ertu_onay")}`)
    let embed = new EmbedBuilder()
      .setImage('attachment://ertu.png')
      .setThumbnail(Ã¼ye.user.displayAvatarURL({ dynamic: true, size: 2048 }))
      .addFields(
        {
          name: `${client.emoji("ertu_star2")} **KullanÄ±cÄ± Bilgisi**`,
          value: `
\` â€¢ \` Profil: ${Ã¼ye}
\` â€¢ \` ID: \`${Ã¼ye.id}\`
\` â€¢ \` OluÅŸturulma Tarihi: <t:${Math.floor(member.user.createdTimestamp / 1000)}:R>
${bilgi}
       `, inline: false
        },
        {
          name: `${client.emoji("ertu_info")} **Sunucu Bilgisi**`,
          value: `
\` â€¢ \` Sunucu Ä°smi: \`${member.displayName}\`
\` â€¢ \` Ceza PuanÄ±: \`${cezapuanData ? cezapuanData.cezapuan : 0}\`
\` â€¢ \` KatÄ±lma Tarihi: <t:${Math.floor(member.joinedAt / 1000)}:R>
\` â€¢ \` KatÄ±lÄ±m SÄ±rasÄ±: \`${(message.guild.members.cache.filter(a => a.joinedTimestamp <= Ã¼ye.joinedTimestamp).size).toLocaleString()}/${(message.guild.memberCount).toLocaleString()}\`
\` â€¢ \` Rolleri: (\`${member.roles.cache.size - 1 >= 0 ? member.roles.cache.size - 1 : 0}\`): ${roleList}
       `, inline: false
        },
      );

      if (coindb.evlilik === true) {
        embed.addFields(
          {
            name: `${client.emoji("ertu_members")} **Sosyal Bilgisi**`,
            value: `
  \` â€¢ \` Evli olduÄŸu kiÅŸi: ${coindb ? `<@${coindb.evlendiÄŸikisiID}>` : "Evli DeÄŸil"}
  \` â€¢ \` Evlenme Tarihi: ${evlendigiTarihi}
  \` â€¢ \` EvlendiÄŸi YÃ¼zÃ¼k: \`${yuzukisim} YÃ¼zÃ¼k\`
       `, inline: false
          }
        )
      }

      if (Ã¼ye && Ã¼ye.presence && Ã¼ye.presence.activities && Ã¼ye.presence.activities.some(x => x.name == "Spotify" && x.type == ActivityType.Listening)) {
        let status = Ã¼ye.presence.activities.find(x => x.name == "Spotify");
        const spotify = await new ertuSpotify()
        .setOverlayOpacity(0.7)
        .setAuthor(status.state)
        .setAlbum(status.assets.largeText)
        .setImage(`https://i.scdn.co/image/${status.assets.largeImage.slice(8)}`)
        .setTimestamp(new Date(Date.now()).getTime() - new Date(status.timestamps.start).getTime(), new Date(status.timestamps.end).getTime() - new Date(status.timestamps.start).getTime())
        .setTitle(status.details)
        .build();
        embed.setImage("attachment://spotify.png");
        obje = { content: ``, embeds: [embed], components: [row], files:[{name:"spotify.png",attachment:spotify}]}
       } else {
        obje = { content: ``, embeds: [embed], components: [row]}
       }

    let ertu = await message.reply({ content: `${client.emoji("ertu_loading")} | **${Ã¼ye.user.username}** isimli Ã¼yenin detaylÄ± bilgileri yÃ¼kleniyor...` })
    ertu.edit(obje)
    var filter = (menu) => menu.user.id === message.author.id;
    const collector = ertu.createMessageComponentCollector({ filter, time: 60000 })

    collector.on("collect", async (menu) => {
      if (menu.values[0] === "avatar") {
        menu.reply({ content: `${Ã¼ye.displayAvatarURL({ dynamic: true, size: 4096 })}`, ephemeral: true })
      }

      if (menu.values[0] === "banner") {
        let banner = await ertuBanner(Ã¼ye.id, client)
        menu.reply({ content: `${banner}`, ephemeral: true })
      }

      if (menu.values[0] === "cezalarim") {
        let kom = client.commands.find(x => x.name == "sicil")
        if (kom) kom.onCommand(client, message, args, ertuembed)
        ertu.delete().catch(err => { })
        menu.deferUpdate().catch(err => { })
      }

      if (menu.values[0] === "sesgecmisim") {
        let kom = client.commands.find(x => x.name == "kanallog")
        if (kom) kom.onCommand(client, message, args, ertuembed)
        ertu.delete().catch(err => { })
        menu.deferUpdate().catch(err => { })
      }

      if (menu.values[0] === "coin") {
        let kom = client.commands.find(x => x.name == "coin")
        if (kom) kom.onCommand(client, message, args, ertuembed)
        ertu.delete().catch(err => { })
        menu.deferUpdate().catch(err => { })
      }

      if (menu.values[0] === "stat") {
        let kom = client.commands.find(x => x.name == "stat")
        if (kom) kom.onCommand(client, message, args, ertuembed)
        ertu.delete().catch(err => { })
        menu.deferUpdate().catch(err => { })
      }

    })
    collector.on("end", () => {
      ertu.delete().catch(err => { })
    })
  },
};

async function ertuBanner(user, client) {
  const response = await axios.get(`https://discord.com/api/v9/users/${user}`, { headers: { 'Authorization': `Bot ${client.token}` } });
  if(!response.data.banner) return `KiÅŸinin banneri yok!`
  if(response.data.banner.startsWith('a_')) return `https://cdn.discordapp.com/banners/${response.data.id}/${response.data.banner}.gif?size=512`
  else return(`https://cdn.discordapp.com/banners/${response.data.id}/${response.data.banner}.png?size=512`)
}