import Color from "color";
import type {Team} from "../types/team.js";
import type {ListPage, PageList} from "../types/page.ts";

export const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);

export const nameRegex = new RegExp("(?!.*\/).+(?=\\.(md|json))");

export function mapToMap(pages: PageList): Map<string, ListPage[]> {
    const map = new Map();
    for (const page of pages) {
        let folder = page.path.substring(0, page.path.indexOf(nameRegex.exec(page.path)!![0]));
        if (!map.has(folder)) {
            map.set(folder, []);
        }
        map.get(folder).push(page);
    }
    return map;
}

export function colorFromTeam(team: Team): string {
    switch (team.color) {
        case "1":
            return "#0000AA";
        case "2":
            return "#00AA00";
        case "3":
            return "#00AAAA";
        case "4":
            return "#AA0000";
        case "5":
            return "#AA00AA";
        case "6":
            return "#FFAA00";
        case "7":
            return "#AAAAAA";
        case "8":
            return "#555555";
        case "9":
            return "#5555FF";
        case "a":
            return "#55FF55";
        case "b":
            return "#55FFFF";
        case "c":
            return "#FF5555";
        case "d":
            return "#FF55FF";
        case "e":
            return "#FFFF55";
        case "f":
            return "#FFFFFF";
        default:
            return "#000000";
    }
}

export function lighten(color: string) {
    return brightness(color) ? Color(color).lighten(0.2).hex() : Color(color).darken(0.2).hex()
}

export function brightness(color: string) {
    return Color(color).isLight()
}

export function base64ToBytes(base64: string) {
    const binString = atob(base64);
    // @ts-ignore
    return Uint8Array.from(binString, (m) => m.codePointAt(0));
}

export function bytesToBase64(bytes: Uint8Array) {
    const binString = String.fromCodePoint(...bytes);
    return btoa(binString);
}
