import axios from "axios";
import i18n from "../config/i18n.js";
import {compareCardOrder, hasEffectCard} from "../hooks/useCard.jsx";

const vite_url = import.meta.env.VITE_URL;

export const apiAxios = axios.create({
    baseURL: `${vite_url}/api`
});
apiAxios.defaults.headers.post['Accept'] = 'application/json; charset=UTF-8';

export function isInClub(userinfo, clubId) {
    return userinfo?.groups.filter((g => g.startsWith("/club/"))).map(g => g.split("/")[2]).map(g => Number(g.split("-")[0])).includes(clubId)
}

export function isClubAdmin(userinfo) {
    return userinfo?.roles?.includes("club_president") || userinfo?.roles?.includes("club_respo_intra")
        || userinfo?.roles?.includes("club_secretaire") || userinfo?.roles?.includes("club_tresorier");
}


export const errFormater = (data, msg) => {
    if (!data)
        return msg
    if (!data.response) {
        if (data.message)
            return `${msg} (${data.message} 😕)`

        if (typeof data === 'string' || data instanceof String) {
            if (/.*D[a-zA-Z]+Exception:.*/.test(data))
                return `${msg} (${data.split(":").slice(1).join(":").trim()} 😕)`
            else
                return `${msg}`
        }
        return `${msg} (${data} 😕)`
    }
    if (typeof data.response.data === 'string' || data.response.data instanceof String)
        return `${msg} (${data.response.statusText}: ${data.response.data}) 😕`
    return `${msg} (${data.response.statusText}: ${JSON.stringify(data.response.data)}) 😕`
}

export const CatList = [
    "SUPER_MINI",
    "MINI_POUSSIN",
    "POUSSIN",
    "BENJAMIN",
    "MINIME",
    "CADET",
    "JUNIOR",
    "SENIOR1",
    "SENIOR2",
    "VETERAN1",
    "VETERAN2"
];

export function sortCategories(catA, catB) {
    const indexA = CatList.indexOf(catA);
    const indexB = CatList.indexOf(catB);

    if (indexA === -1 && indexB === -1) {
        return 0; // Both categories are unknown, maintain their order
    } else if (indexA === -1) {
        return 1; // catA is unknown, place it after catB
    } else if (indexB === -1) {
        return -1; // catB is unknown, place it after catA
    } else {
        return indexA - indexB; // Both categories are known, sort by their indices
    }
}

export function applyOverCategory(cat, overCat) {
    const catIndex = CatList.indexOf(cat) + overCat;
    if (catIndex < 0) {
        return CatList[0];
    } else if (catIndex >= CatList.length) {
        return CatList[CatList.length - 1];
    } else {
        return CatList[catIndex];
    }
}

export function getCategoryFormBirthDate(birth_date, currentDate = new Date()) {
    const currentSaison = getSaison(currentDate)
    const birthYear = birth_date.getFullYear()

    const diff = currentSaison - birthYear;
    if (diff < 6) {
        return "SUPER_MINI";
    } else if (diff < 8) {
        return "MINI_POUSSIN";
    } else if (diff < 10) {
        return "POUSSIN";
    } else if (diff < 12) {
        return "BENJAMIN";
    } else if (diff < 14) {
        return "MINIME";
    } else if (diff < 16) {
        return "CADET";
    } else if (diff < 18) {
        return "JUNIOR";
    } else if (diff < 25) {
        return "SENIOR1";
    } else if (diff < 35) {
        return "SENIOR2";
    } else if (diff < 45) {
        return "VETERAN1";
    } else {
        return "VETERAN2";
    }
}

export function getSaison(currentDate = new Date()) {
    if (currentDate.getMonth() >= 8) { //septembre et plus
        return currentDate.getFullYear()
    } else {
        return currentDate.getFullYear() - 1
    }
}

export function getCatName(cat) {
    switch (cat) {
        case "SUPER_MINI":
            return i18n.t('cat.superMini');
        case "MINI_POUSSIN":
            return i18n.t('cat.miniPoussin');
        case "POUSSIN":
            return i18n.t('cat.poussin');
        case "BENJAMIN":
            return i18n.t('cat.benjamin');
        case "MINIME":
            return i18n.t('cat.minime');
        case "CADET":
            return i18n.t('cat.cadet');
        case "JUNIOR":
            return i18n.t('cat.junior');
        case "SENIOR1":
            return i18n.t('cat.senior1');
        case "SENIOR2":
            return i18n.t('cat.senior2');
        case "VETERAN1":
            return i18n.t('cat.vétéran1');
        case "VETERAN2":
            return i18n.t('cat.vétéran2');
        case null:
            return i18n.t('cat.catégorieInconnue');
        default:
            return cat;
    }
}

export function getCatFromName(name) {
    switch (name.toLowerCase()) {
        case i18n.t('cat.superMini').toLowerCase():
            return "SUPER_MINI";
        case i18n.t('cat.miniPoussin').toLowerCase():
            return "MINI_POUSSIN";
        case i18n.t('cat.poussin').toLowerCase():
            return "POUSSIN";
        case i18n.t('cat.benjamin').toLowerCase():
            return "BENJAMIN";
        case i18n.t('cat.minime').toLowerCase():
            return "MINIME";
        case i18n.t('cat.cadet').toLowerCase():
            return "CADET";
        case i18n.t('cat.junior').toLowerCase():
            return "JUNIOR";
        case i18n.t('cat.senior1').toLowerCase():
            return "SENIOR1";
        case i18n.t('cat.senior2').toLowerCase():
            return "SENIOR2";
        case i18n.t('cat.vétéran1').toLowerCase():
            return "VETERAN1";
        case i18n.t('cat.vétéran2').toLowerCase():
            return "VETERAN2";
        default:
            return name;
    }
}

export const SwordList = [
    "NONE",
    "ONE_HAND",
    "TWO_HAND",
    "SABER"
]

export function getSwordTypeName(type) {
    switch (type) {
        case "NONE":
            return i18n.t('sword.none');
        case "ONE_HAND":
            return i18n.t('sword.oneHand');
        case "TWO_HAND":
            return i18n.t('sword.twoHand');
        case "SABER":
            return i18n.t('sword.saber');
        default:
            return type;
    }
}

export function getSwordSize(type, cat, gender) {
    const catIndex = CatList.indexOf(cat)
    if (type === "ONE_HAND") {
        if (catIndex <= 1) {
            return "XS"
        } else if (catIndex <= 3) {
            return "S"
        } else if (catIndex <= 6 || gender === "F") {
            return "M"
        } else {
            return "L"
        }
    } else if (type === "TWO_HAND") {
        if (catIndex <= 5) {
            return "--"
        } else if (catIndex <= 6 || gender === "F") {
            return "XL"
        } else {
            return "XXL"
        }
    } else if (type === "SABER") {
        if (catIndex <= 3) {
            return "--"
        } else if (catIndex <= 6) {
            return "S"
        } else {
            return "L"
        }
    }
    return "--"
}

export const ShieldList = [
    "NONE",
    "STANDARD",
    "ROUND",
    "TEARDROP",
    "BUCKLER"
]

export function getShieldTypeName(type) {
    switch (type) {
        case "NONE":
            return i18n.t('shield.none');
        case "STANDARD":
            return i18n.t('shield.standard');
        case "ROUND":
            return i18n.t('shield.round');
        case "TEARDROP":
            return i18n.t('shield.teardrop');
        case "BUCKLER":
            return i18n.t('shield.buckler');
        default:
            return type;
    }
}

export function getShieldSize(type, cat) {
    if (type === "STANDARD") {
        const catIndex = CatList.indexOf(cat)
        if (catIndex <= 1) {
            return "S"
        } else {
            return "L"
        }
    }
    return "--"
}

export function getToastMessage(msgKey, ns = 'common') {
    return {
        pending: i18n.t(msgKey + '.pending', {ns}),
        success: i18n.t(msgKey + '.success', {ns}),
        error: {
            render({data}) {
                return errFormater(data, i18n.t(msgKey + '.error', {ns}))
            }
        }
    }
}

export function win(match, cards = []) {
    const cards2 = cards.filter(c => (c.comb === match.c1 || c.comb === match.c2) && hasEffectCard(c, match.id, match.categorie)).sort(compareCardOrder).pop()

    if (cards2) {
        if (cards2.comb === match.c1)
            return 1
        else
            return -1
    }

    let sum = 0
    for (const score of match?.scores) {
        if (score.s1 === -1000 || score.s2 === -1000) continue
        if (score.s1 > score.s2) sum++
        else if (score.s1 < score.s2) sum--
    }
    return sum
}

export function win_end(match, cards = []) {
    const cards2 = cards?.filter(c => (c.comb === match.c1 || c.comb === match.c2) && hasEffectCard(c, match.id, match.categorie)).sort(compareCardOrder)

    if (cards2.length > 1) {
        if (cards2[0].comb !== cards2[1].comb)
            return {win: 0, end: true}
    }
    if (cards2.length > 0) {
        if (cards2[0].comb === match.c1)
            return {win: -1, end: true}
        else
            return {win: 1, end: true}
    }


    let sum = 0
    for (const score of match?.scores) {
        if (score.s1 === -1000 || score.s2 === -1000) continue
        if (score.s1 > score.s2) sum++
        else if (score.s1 < score.s2) sum--
    }
    return {win: sum, end: match?.end}
}

export function virtual_end(match, cards) {
    if (!cards)
        return false
    return cards.some(c => (c.comb === match?.c1 || c.comb === match?.c2) && hasEffectCard(c, match.id, match.categorie))
}

export function virtualScore(combId, score, match, cards) {
    const cards2 = cards?.filter(c => (c.comb === match?.c1 || c.comb === match?.c2) && hasEffectCard(c, match.id, match.categorie)).sort(compareCardOrder)

    if (cards2.length > 1) {
        if (cards2[0].comb !== cards2[1].comb)
            return -997
    }
    if (cards2.length > 0) {
        if (cards2[0].comb === combId)
            return -997
        else
            return 10
    }

    if (combId === match?.c1) {
        return score.s1
    } else if (combId === match?.c2) {
        return score.s2
    } else {
        return ""
    }
}

export function scorePrint(s1) {

    switch (s1) {
        case -997:
            return "disc."
        case -998:
            return "abs."
        case -999:
            return "for."
        case -1000:
            return ""
        default:
            return String(s1)
    }
}

export function timePrint(time, negSign = false) {
    if (time === null || time === undefined)
        return ""
    const neg = time < 0
    if (neg) {
        if (!negSign)
            return "00:00"
        time = -time
    }

    const ms = time % 1000
    time = (time - ms) / 1000
    const sec = time % 60
    time = (time - sec) / 60
    const min = time % 60
    const hr = (time - min) / 60

    return (neg ? "-" : "") +
        (hr > 0 ? String(hr).padStart(2, '0') + ":" : "") +
        String(min).padStart(2, '0') + ":" +
        String(sec).padStart(2, '0')
}

//create full hex
function fullHex(hex) {
    let r = hex.slice(1, 2);
    let g = hex.slice(2, 3);
    let b = hex.slice(3, 4);

    r = parseInt(r + r, 16);
    g = parseInt(g + g, 16);
    b = parseInt(b + b, 16);

    // return {r, g, b}
    return {r, g, b};
}

//convert hex to rgb
export function hex2rgb(hex) {
    if (hex.length === 4) {
        return fullHex(hex);
    }

    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);

    // return {r, g, b}
    return {r, g, b};
}

export function toDataURL(src, outputFormat) {
    return  new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'Anonymous';
        img.onload = function() {
            const canvas = document.createElement('CANVAS');
            const ctx = canvas.getContext('2d');
            let dataURL;
            canvas.height = this.naturalHeight;
            canvas.width = this.naturalWidth;
            ctx.drawImage(this, 0, 0);
            dataURL = canvas.toDataURL(outputFormat);
            resolve(dataURL);
        };
        img.onerror = function() {
            reject(new Error('Could not load image at ' + src));
        }

        img.src = src;
        if (img.complete || img.complete === undefined) {
            img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
            img.src = src;
        }
    });
}
