import { TableManager } from "../../Engine/CatanEngine/TableV3/TableManager";
import { Tools } from "../../Tools";

export class MainControl {

    //#region DownloadForm Function

    /**
     * 載入外載表設定檔
     * @param formtype FormType
     */
    public static async DownloadForm(formtype: DownloadForm.FormType): Promise<void> {
        if (DownloadForm.DownloadFormData.DownloadSuccess.has(formtype)) {
            console.warn(`CSSettingsV3 ${formtype} 已經載過`);
            return;
        }
        DownloadForm.DownloadFormData.DownloadSuccess.set(formtype, true);
        let needForm: string[] = DownloadForm.DownloadFormData[`${formtype}Form`];
        let parallel: Promise<void>[] = [];
        for (let i: number = 0; i < needForm.length; i++) {
            parallel.push(this.DownloadFormSetting(needForm[i]));
        }
        // set Form
        await Promise.all(parallel);
    }

    /**
     * 載入外載表設定檔
     * @param formname 設定檔名稱
     */
    public static async DownloadFormSetting(formname: string): Promise<void> {
        // http://patch-dev.online-bj.com/shared/jsons/slot_050.json
        let fileUrl: string = `${formname}.json`;
        fileUrl = "http://patch-dev.online-bj.com/shared/jsons/" + fileUrl;
        fileUrl = fileUrl + "?v=" + Date.now();
        let isdownloading: boolean = true;
        let xhr: XMLHttpRequest = new XMLHttpRequest();
        // xhr.withCredentials = true;
        xhr.onreadystatechange = function (): void {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 400)) {
                let res: any = {};
                res.json = JSON.parse(xhr.responseText);
                res.name = formname;
                TableManager.AddJsonAsset(res);
                isdownloading = false;
            }
        };
        xhr.open("GET", fileUrl);
        xhr.send();
        while (isdownloading) {
            await Tools.Sleep(100);
        }
    }

    //#endregion
}
export default MainControl;

//#region DownloadForm
export module DownloadForm {
    export enum FormType {
        Formread = "formread",
    }

    export class DownloadFormData {

        /** 已下載的表 */
        public static DownloadSuccess: Map<string, boolean> = new Map<string, boolean>();

        /** Bag需要的表(xxxx.json) */
        public static formreadForm: string[] = ["formread", "slotset"];
    }
}

//#endregion