/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable prefer-rest-params */
import './global-setup.mjs';

import * as GC from '@mescius/spread-sheets';
import '@mescius/spread-sheets-barcode';
import '@mescius/spread-sheets-shapes';
import '@mescius/spread-sheets-charts';
import "@mescius/spread-sheets-pivot-addon";
import '@mescius/spread-sheets-print';
import '@mescius/spread-sheets-io';
import "@mescius/spread-sheets-collaboration-addon";

// need add LicenseKey for spreadJS
// GC.Spread.Sheets.LicenseKey = "";
if (!GC.Spread.Sheets.LicenseKey) {
    console.warn("If need to use the import, need to set the spreadJS license");
}

export function importFile(fileBlob) {
    return new Promise((resolve, reject) => {
        const rejectError = (e) => {
            if (!GC.Spread.Sheets.LicenseKey) {
                console.error('Need add LicenseKey for SpreadJS');
                reject(new Error("Need add LicenseKey for SpreadJS"));
            }
            else {
                console.error('import error', e);
                reject(new Error("import error"));
            }
        };

        if (!fileBlob || !fileBlob.name) {
            return rejectError(new Error("Invalid file"));
        }

        const spread = new GC.Spread.Sheets.Workbook();
        const fileExtension = fileBlob.name.slice(fileBlob.name.lastIndexOf('.')).toLowerCase();
        switch (fileExtension) {
            case '.xlsx':
                spread.import(fileBlob, () => {
                    resolve(spread.collaboration.toSnapshot());
                }, () => {
                    rejectError(new Error("Error loading .xlsx file"));
                }, {
                    fileType: GC.Spread.Sheets.FileType.excel
                });
                break;
            case '.sjs':
                spread.open(fileBlob, () => {
                    resolve(spread.collaboration.toSnapshot());
                }, () => {
                    rejectError(new Error("Error loading .sjs file"));
                });
                break;
            case '.ssjson':
                spread.import(fileBlob, () => {
                    resolve(spread.collaboration.toSnapshot());
                }, () => {
                    rejectError(new Error("Error loading .ssjson file"));
                }, {
                    fileType: GC.Spread.Sheets.FileType.ssjson
                });
                break;
        }
    });
}
