import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();

const lolaccount = process.env.lol_account;
const lolmatch = process.env.lol_match;
const header = { headers: { 'X-Riot-Token': process.env.keyLol }};

export default class Manager {

    async getInfo(name) {
        const user0 = await this.getAccountByName(name);
        if (!user0?.puuid) {
            return {error: 'Pseudo invalide'};
        }
        const listMatch = await this.getMatchByUuid(user0.puuid);
        const lastMatchInfo = await this.getInfoByMatchId(listMatch[0]);
        let allUser = lastMatchInfo.info.participants;
        allUser = allUser.map(x => ({
            puuid: x.puuid,
            champion: x.championName,
            kda: `${x.kills}/${x.deaths}/${x.assists}`,
            resultat: x.win ? 'Victoire' : 'Defaite'
        }));
        let results = [];
        for (const user of allUser) {
            let nameLevel = await this.getNameLevelByUuid(user.puuid);
            delete user.puuid;
            results.push({...nameLevel, ...user});
        }
        return results;
    }

    async getAccountByName(name) {
        let response = {};
        try {
            response = await axios.get(`${lolaccount}/lol/summoner/v4/summoners/by-name/${encodeURIComponent(name)}`, header);
        } catch(e) {
            console.log(e);
        }
        return response.data;
    }

    async getMatchByUuid(uuid) {
        let response = {};
        try {
            response = await axios.get(`${lolmatch}/lol/match/v5/matches/by-puuid/${encodeURIComponent(uuid)}/ids`, header);
        } catch(e) {
            console.log(e);
        }
        return response.data;
    }

    async getInfoByMatchId(id) {
        let response = {};
        try {
            response = await axios.get(`${lolmatch}/lol/match/v5/matches/${encodeURIComponent(id)}`, header);
        } catch(e) {
            console.log(e);
        }
        return response.data;
    }

    async getNameLevelByUuid(uuid) {
        let response = {};
        try {
            response = await axios.get(`${lolaccount}/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(uuid)}`, header);
        } catch(e) {
            console.log(e);
        }
        return {name: response.data.name, level: response.data.summonerLevel};
    }
}