import * as fs from "fs";
import * as path from "path";
import recursiveReadDir from "recursive-readdir"
import {isNumber} from "util";
import FormData from "form-data";
import axios from "axios";
import CardInfo from "./cardInfo.json"

let regex = /(?<Name>[a-zA-Z0-9-]+).(?<Format>[a-zA-Z]+)/

let token : string;

let api = 'http://localhost/api'

async function importFiles(cardInfo : any){
    let { data } = await axios.post(`${api}/login`, {
        username: "admin",
        password: "admin"
    });
    axios.interceptors.request.use(function (config) {
        config.headers.Authorization =  `Bearer ${data.token}`;
        return config;
    });
    let cards = await axios.get(`${api}/card/`)
    cards.data.forEach((card : any) => {
        axios.delete(`${api}/card/` + card._id)
    })

    let filesToDelete = await axios.get(`${api}/file/`)
    filesToDelete.data.forEach((file : any) => {
        axios.delete(`${api}/file/${file._id}`)
    })

    recursiveReadDir(path.join(__dirname, "/cards"), ["background.png"], (err, files) => {
        files.forEach(async (file: string) => {
            let tempDir = path.dirname(file).split('/').pop() || "";

            const dir = tempDir as keyof typeof cardInfo;
            const match = path.basename(file).match(regex);
            if (match) {
                let groups: any = match["groups"];
                let cardColor: string = path.basename(path.dirname(file));
                let cardName = isNumber(groups.Name) ? Number(groups.Name) : groups.Name;
                let cardBackImage = path.join(path.dirname(file), "background.png");
                let searchColour = cardColor;
                if (cardColor === "blue" || cardColor === "green" || cardColor === "red" || cardColor === "yellow") {
                    searchColour = "colour";
                }
                let cardInfos = cardInfo[searchColour].find((d: any) => d.card === cardName);

                const formFrontImage = new FormData();
                formFrontImage.append('file', fs.createReadStream(file));

                const request_config_frontImage = {
                    headers: formFrontImage.getHeaders()
                };

                let frontImage = await axios.post(`${api}/file/`, formFrontImage, request_config_frontImage);

                const formBackImage = new FormData();
                formBackImage.append('file', fs.createReadStream(cardBackImage));

                const request_config_backImage = {
                    headers: formBackImage.getHeaders()
                };

                let backImage = await axios.post(`${api}/file/`, formBackImage, request_config_backImage);


                let card: any = {
                    name: cardName,
                    color: cardColor,
                    value: cardInfos?.value,
                    count: cardInfos?.count,
                    info: cardInfos?.info,
                    special: cardInfos?.special,
                    frontImage: frontImage.data._id,
                    backImage: backImage.data._id,
                };

                const cardForm = new FormData();
                cardForm.append("name", cardColor + " " + cardName);
                cardForm.append("color", cardColor);
                cardForm.append("value", cardInfos?.value);
                cardForm.append("count", cardInfos?.count);
                cardForm.append("info", cardInfos?.info);
                cardForm.append("special", cardInfos?.special);
                cardForm.append("frontImage", frontImage.data._id);
                cardForm.append("backImage", backImage.data._id);

                let card2 = await axios.post(`${api}/card/`, card);

            } else {
                console.error(`Failed to import ${file}`);
            }
        });
    })
}

importFiles(CardInfo)



