const Command = require("../../Class/Command.js");
const { Message, RichEmbed } = require("eris");
const SummonerData = require("../../Class/SummonerData.js");
const generateEmbed = require("../../Functions/generateEmbed.js");
const regions_array = require("../../js/regions.js");
const emojiWHithSpell = require("../../json/spells.json");
const emojiWithChampion = require("../../js/championsEmoji.js");

module.exports = class Matchlist extends Command {
  constructor(client) {
    super(client, {
      name: "matchlist",
      aliases: ["ml"],
      description: "Muestra las ultimas 5 partidas del invocador.",
      usage: "matchlist <región> <invocador>",
      example: "matchlist LAN TheEaterOfSouls",
      category: "LoL",
      PermissionsBot: ["viewChannel", "sendMessages", "embedLinks"],
      PermissionsUser: [],
      cooldown: 15,
      nsfw: false,
      args: true,
      dev: false,
      enable: true,
    });
  }
  /**
   *
   * @param {Message} message
   * @returns
   */
  async run(message, args) {
    const client = this.client;
    try {
      let region = args[0];
      let region_final;
      const username = args.slice(1).join(" ");

      if (!region)
        return generateEmbed(
          message,
          client.color,
          `Comando ${this.information.name}`,
          "Ingresa la región del invocador el cual deseas obtener la información.",
          true,
          "Uso correcto:",
          `${await client.guildPrefix(message)}${this.information.usage}`
        );

      if (region) {
        region = region.toLowerCase();
        region = region.replace(/[0-9]/g, "");
      }

      switch (region) {
        case "ru":
        case "kr":
          region_final = region;
          break;
        case "lan":
          region_final = "la1";
          break;
        case "las":
          region_final = "la2";
          break;
        case "oce":
          region_final = "oc1";
          break;
        case "eune":
          region_final = "eun1";
          break;
        default:
          region_final = `${region}1`;
          break;
      }

      if (!regions_array.includes(region_final))
        return generateEmbed(
          message,
          client.color,
          `Comando ${this.information.name}`,
          "Ingresa una región de invocador válida:\n`LAN, LAS, NA, RU, KR, EUW, EUNE, BR, TR, KR, JP`.",
          false
        );

      if (!username)
        return generateEmbed(
          message,
          client.color,
          `Comando ${this.information.name}`,
          "Ingresa el nombre del invocador del cual deseas obtener la información.",
          true,
          "Uso correcto:",
          `${await client.guildPrefix(message)}${this.information.usage}`
        );

      const summonerData = new SummonerData(region, username);
      const patch = await summonerData.getCurrentPatch();
      const { name: summonerName, profileIconId } =
        await summonerData.profileBasicData();

      const lastPlayedMatch = await summonerData.lastPlayedMatch();
      if (!lastPlayedMatch)
        return generateEmbed(
          message,
          client.color,
          `Comando ${this.information.name}`,
          "Este invocador no tiene partidas.",
          false
        );

      const embed = new RichEmbed()
        .setTitle(
          `> Lista de partidas de: **\`${summonerName}\`** - **\`${region.toUpperCase()}\`**`
        )
        .setThumbnail(
          `http://ddragon.leagueoflegends.com/cdn/${patch}/img/profileicon/${profileIconId}.png`
        )
        .setColor(client.color);
      if (lastPlayedMatch[0]) {
        const { time, mode, map, spells } = lastPlayedMatch[0];
        const {
          win,
          kills,
          deaths,
          assists,
          totalMinionsKilled,
          neutralMinionsKilled,
        } = lastPlayedMatch[0].stats;
        const { name: championName } = lastPlayedMatch[0].stats.champion;
        embed.addField(
          "**`Partida 1:`**",
          `${getMapNameEs(map)} (${mode}) (${time[1]}).\n${
            win ? ":green_circle:" : ":red_circle:"
          } ${deaths == 0 && kills > 1 ? "`" + "KDA Perfecto" + "`.\n" : ""} ${
            emojiWithChampion[`${championName}`]
          } **${championName}** con **${kills}/${deaths}/${assists}** (${
            isNaN(kills + assists / deaths)
              ? "00.0"
              : (kills + assists / deaths).toFixed(1)
          }%) y **${
            totalMinionsKilled + neutralMinionsKilled
          }CS**.\n**Spells:** ${emojiWHithSpell[`${spells.spell1Id}`]}${
            emojiWHithSpell[`${spells.spell2Id}`]
          }.\n${time[0]}.`
        );
      }
      if (lastPlayedMatch[1]) {
        const { time, mode, map, spells } = lastPlayedMatch[1];
        const {
          win,
          kills,
          deaths,
          assists,
          totalMinionsKilled,
          neutralMinionsKilled,
        } = lastPlayedMatch[1].stats;
        const { name: championName } = lastPlayedMatch[1].stats.champion;
        embed.addField(
          "**`Partida 2:`**",
          `${getMapNameEs(map)} (${mode}) (${time[1]}).\n${
            win ? ":green_circle:" : ":red_circle:"
          } ${deaths == 0 && kills > 1 ? "`" + "KDA Perfecto" + "`.\n" : ""} ${
            emojiWithChampion[`${championName}`]
          } **${championName}** con **${kills}/${deaths}/${assists}** (${
            isNaN(kills + assists / deaths)
              ? "00.0"
              : (kills + assists / deaths).toFixed(1)
          }%) y **${
            totalMinionsKilled + neutralMinionsKilled
          }CS**.\n**Spells:** ${emojiWHithSpell[`${spells.spell1Id}`]}${
            emojiWHithSpell[`${spells.spell2Id}`]
          }.\n${time[0]}.`
        );
      }
      if (lastPlayedMatch[2]) {
        const { time, mode, map, spells } = lastPlayedMatch[2];
        const {
          win,
          kills,
          deaths,
          assists,
          totalMinionsKilled,
          neutralMinionsKilled,
        } = lastPlayedMatch[2].stats;
        const { name: championName } = lastPlayedMatch[2].stats.champion;
        embed.addField(
          "**`Partida 3:`**",
          `${getMapNameEs(map)} (${mode}) (${time[1]}).\n${
            win ? ":green_circle:" : ":red_circle:"
          } ${deaths == 0 && kills > 1 ? "`" + "KDA Perfecto" + "`.\n" : ""} ${
            emojiWithChampion[`${championName}`]
          } **${championName}** con **${kills}/${deaths}/${assists}** (${
            isNaN(kills + assists / deaths)
              ? "00.0"
              : (kills + assists / deaths).toFixed(1)
          }%) y **${
            totalMinionsKilled + neutralMinionsKilled
          }CS**.\n**Spells:** ${emojiWHithSpell[`${spells.spell1Id}`]}${
            emojiWHithSpell[`${spells.spell2Id}`]
          }.\n${time[0]}.`
        );
      }
      if (lastPlayedMatch[3]) {
        const { time, mode, map, spells } = lastPlayedMatch[3];
        const {
          win,
          kills,
          deaths,
          assists,
          totalMinionsKilled,
          neutralMinionsKilled,
        } = lastPlayedMatch[3].stats;
        const { name: championName } = lastPlayedMatch[3].stats.champion;
        embed.addField(
          "**`Partida 4:`**",
          `${getMapNameEs(map)} (${mode}) (${time[1]}).\n${
            win ? ":green_circle:" : ":red_circle:"
          } ${deaths == 0 && kills > 1 ? "`" + "KDA Perfecto" + "`.\n" : ""} ${
            emojiWithChampion[`${championName}`]
          } **${championName}** con **${kills}/${deaths}/${assists}** (${
            isNaN(kills + assists / deaths)
              ? "00.0"
              : (kills + assists / deaths).toFixed(1)
          }%) y **${
            totalMinionsKilled + neutralMinionsKilled
          }CS**.\n**Spells:** ${emojiWHithSpell[`${spells.spell1Id}`]}${
            emojiWHithSpell[`${spells.spell2Id}`]
          }.\n${time[0]}.`
        );
      }
      if (lastPlayedMatch[4]) {
        const { time, mode, map, spells } = lastPlayedMatch[4];
        const {
          win,
          kills,
          deaths,
          assists,
          totalMinionsKilled,
          neutralMinionsKilled,
        } = lastPlayedMatch[4].stats;
        const { name: championName } = lastPlayedMatch[4].stats.champion;
        embed.addField(
          "**`Partida 5:`**",
          `${getMapNameEs(map)} (${mode}) (${time[1]}).\n${
            win ? ":green_circle:" : ":red_circle:"
          } ${deaths == 0 && kills > 1 ? "`" + "KDA Perfecto" + "`.\n" : ""} ${
            emojiWithChampion[`${championName}`]
          } **${championName}** con **${kills}/${deaths}/${assists}** (${
            isNaN(kills + assists / deaths)
              ? "00.0"
              : (kills + assists / deaths).toFixed(1)
          }%) y **${
            totalMinionsKilled + neutralMinionsKilled
          }CS**.\n**Spells:** ${emojiWHithSpell[`${spells.spell1Id}`]}${
            emojiWHithSpell[`${spells.spell2Id}`]
          }.\n${time[0]}.`
        );
      }

      message.channel.createMessage({ embeds: [embed] });
    } catch (error) {
      client.createMessage(
        message.channel.id,
        client.markdown(`Error: ${error.message}`, "js")
      );
    }
  }
};

function getMapName(id) {
  const maps = [
    {
      mapId: 1,
      mapName: "Grieta del Invocador",
      notes: "Original Summer variant",
    },
    {
      mapId: 2,
      mapName: "Grieta del Invocador",
      notes: "Original Autumn variant",
    },
    {
      mapId: 3,
      mapName: "El campo de pruebas",
      notes: "Tutorial Map",
    },
    {
      mapId: 4,
      mapName: "El Bosque Retorcido",
      notes: "Original Version",
    },
    {
      mapId: 8,
      mapName: "La Cicatriz de Cristal",
      notes: "Dominion map",
    },
    {
      mapId: 10,
      mapName: "El Bosque Retorcido",
      notes: "Last TT map",
    },
    {
      mapId: 11,
      mapName: "Grieta del Invocador",
      notes: "Current Version",
    },
    {
      mapId: 12,
      mapName: "Abismo de los Lamentos",
      notes: "ARAM map",
    },
    {
      mapId: 14,
      mapName: "Puente del Carnicero",
      notes: "Alternate ARAM map",
    },
    {
      mapId: 16,
      mapName: "Ruinas cósmicas",
      notes: "Dark Star: Singularity map",
    },
    {
      mapId: 18,
      mapName: "Parque de la ciudad de Valoran",
      notes: "Star Guardian Invasion map",
    },
    {
      mapId: 19,
      mapName: "Infraestructura 43",
      notes: "PROJECT: Hunters map",
    },
    {
      mapId: 20,
      mapName: "Lugar de la colisión",
      notes: "Odyssey: Extraction map",
    },
    {
      mapId: 20,
      mapName: "Convergencia",
      notes: "Teamfight Tactics map",
    },
    {
      mapId: 21,
      mapName: "Nexus Blitz",
      notes: "Nexus Blitz map",
    },
  ];
  return maps.find((x) => x.mapId == id).mapName;
}

function getMapNameEs(mapName_1) {
  const maps_2 = [
    {
      mapEs: "Grieta del Invocador",
      mapName: "Summoner's Rift",
      notes: "Original Summer variant",
    },
    {
      mapEs: "Grieta del Invocador",
      mapName: "Summoner's Rift",
      notes: "Original Autumn variant",
    },
    {
      mapEs: "El campo de pruebas",
      mapName: "The Proving Grounds",
      notes: "Tutorial Map",
    },
    {
      mapEs: "El Bosque Retorcido",
      mapName: "Twisted Treeline",
      notes: "Original Version",
    },
    {
      mapEs: "La Cicatriz de Cristal",
      mapName: "The Crystal Scar",
      notes: "Dominion map",
    },
    {
      mapEs: "El Bosque Retorcido",
      mapName: "Twisted Treeline",
      notes: "Last TT map",
    },
    {
      mapEs: "Grieta del Invocador",
      mapName: "Summoner's Rift",
      notes: "Current Version",
    },
    {
      mapEs: "Abismo de los Lamentos",
      mapName: "Howling Abyss",
      notes: "ARAM map",
    },
    {
      mapEs: "Puente del Carnicero",
      mapName: "Butcher's Bridge",
      notes: "Alternate ARAM map",
    },
    {
      mapEs: "Ruinas cósmicas",
      mapName: "Cosmic Ruins",
      notes: "Dark Star: Singularity map",
    },
    {
      mapEs: "Parque de la ciudad de Valoran",
      mapName: "Valoran City Park",
      notes: "Star Guardian Invasion map",
    },
    {
      mapEs: "Infraestructura 43",
      mapName: "Substructure 43",
      notes: "PROJECT: Hunters map",
    },
    {
      mapEs: "Lugar de la colisión",
      mapName: "Crash Site",
      notes: "Odyssey: Extraction map",
    },
    {
      mapEs: "Convergencia",
      mapName: "Convergence",
      notes: "Teamfight Tactics map",
    },
    {
      mapEs: "Nexus Blitz",
      mapName: "Nexus Blitz",
      notes: "Nexus Blitz map",
    },
  ];
  return maps_2.find((x) => x.mapName == mapName_1).mapEs;
}

function getGameModeES(gameModeEN) {
  const gameModes = [
    {
      gameModeEN: "CLASSIC",
      gameModeES: "Clásica",
      description: "Classic Summoner's Rift and Twisted Treeline games",
    },
    {
      gameModeEN: "ODIN",
      gameModeES: "League of Legends: Dominio",
      description: "Dominion/Crystal Scar games",
    },
    {
      gameModeEN: "ARAM",
      gameModeES: "ARAM",
      description: "ARAM games",
    },
    {
      gameModeEN: "TUTORIAL",
      gameModeES: "Tutorial",
      description: "Tutorial games",
    },
    {
      gameModeEN: "URF",
      gameModeES: "URF: Fuego Ultra Rápido",
      description: "URF games",
    },
    {
      gameModeEN: "DOOMBOTSTEEMO",
      gameModeES: "Doom Bots: Bots malditos",
      description: "Doom Bot games",
    },
    {
      gameModeEN: "ONEFORALL",
      gameModeES: "Uno para Todos",
      description: "One for All games",
    },
    {
      gameModeEN: "ASCENSION",
      gameModeES: "Ascensión",
      description: "Ascension games",
    },
    {
      gameModeEN: "FIRSTBLOOD",
      gameModeES: "Duelo de las Nieves",
      description: "Snowdown Showdown games",
    },
    {
      gameModeEN: "KINGPORO",
      gameModeES: "La leyenda del Rey Poro",
      description: "Legend of the Poro King games",
    },
    {
      gameModeEN: "SIEGE",
      gameModeES: "Asedio al Nexo",
      description: "Nexus Siege games",
    },
    {
      gameModeEN: "ASSASSINATE",
      gameModeES: "La caza de la luna de sangre",
      description: "Blood Hunt Assassin games",
    },
    {
      gameModeEN: "ARSR",
      gameModeES: "Todos Aleatorios en la Grieta del Invocador",
      description: "All Random Summoner's Rift games",
    },
    {
      gameModeEN: "DARKSTAR",
      gameModeES: "Estrella Oscura: Singularidad",
      description: "Dark Star: Singularity games",
    },
    {
      gameModeEN: "STARGUARDIAN",
      gameModeES: "Guardianes Estelares: Invasión",
      description: "Star Guardian Invasion games",
    },
    {
      gameModeEN: "PROJECT",
      gameModeES: "PROYECTO: Cazadores",
      description: "PROJECT: Hunters games",
    },
    {
      gameModeEN: "GAMEMODEX",
      gameModeES: "Bombardeo al nexo",
      description: "Nexus Blitz games",
    },
    {
      gameModeEN: "ODYSSEY",
      gameModeES: "Odisea : Extraccion",
      description: "Odyssey: Extraction games",
    },
    {
      gameModeEN: "NEXUSBLITZ",
      gameModeES: "Bombardeo al nexo",
      description: "Nexus Blitz games",
    },
    {
      gameModeEN: "ULTBOOK",
      gameModeES: "Libro de Hechizos Definitivo",
      description: "Ultimate Spellbook games",
    },
  ];

  return gameModes.find((x) => x.gameModeEN == gameModeEN).gameModeES;
}
// const userMatchesData = await summonerData.getMatchesBySummoner(accountId);

// const matches = new Array();
// userMatchesData.matches.map((match) => {
//   matches.push(match.gameId);
// });

// const Ids = matches;
// const avancedData = new Array();
// for (let IDs of Ids) {
//   const advencedMatchData = await summonerData.advencedMatchInfo(IDs);
//   avancedData.push(advencedMatchData);
// }

// let summonerPosition;
// summonerPosition = avancedData
//   .filter((x) => !!x)
//   .map(
//     (x) =>
//       x.participantIdentities.find(
//         (x) => x.player.accountId === accountId
//       )?.participantId
//   );
// let teamsId = new Array();
// for (let pos of summonerPosition) {
//   const teamId = avancedData.map(
//     (x) => x.participants.find((x) => x?.participantId === pos)?.teamId
//   )?.[0];
//   if (teamId) teamsId.push(teamId);
// }
// const gameSummonerInfo = new Array();
// for (let data of summonerPosition) {
//   const dataEnd = avancedData.map((x) =>
//     x.participants.find((x) => x.participantId === data)
//   )[0];
//   const mapName = avancedData.map((x) => getMapName(x.mapId));
//   gameSummonerInfo.push({ ...dataEnd, mapNames: mapName });
// }
// const data = [];
// for (const gameInfo of gameSummonerInfo) {
//   if (!gameInfo?.stats) continue;
//   let str = "```coffeescript\n";
//   str += (gameInfo.stats.win ? "Victoria" : "Derrota") + "\n";
//   const uData = await summonerData.getChampionById(gameInfo.championId);
//   str +=
//     uData.name +
//     " | " +
//     gameInfo.stats.champLevel +
//     " | " +
//     gameInfo.mapNames[0] +
//     "\n";
//   str +=
//     "KDA: " +
//     gameInfo.stats.kills +
//     "/" +
//     gameInfo.stats.deaths +
//     "/" +
//     gameInfo.stats.assists;
//   str +=
//     " | CS: " +
//     Math.max(
//       ["totalMinionsKilled", "neutralMinionsKilled"].reduce(
//         (a, b) => a + gameInfo.stats[b],
//         0
//       ),
//       0
//     );
//   str += " | Oro: " + gameInfo.stats.goldEarned;
//   str += "\n```";
//   data.push(str);
// }
