import { axisGeometryKeys, syncAxisMetadataBucket } from '../workbook-axis-records.js';
import { hasPreservedSheetMetadata, pickPreservedSheetMetadata, pickPreservedWorkbookMetadata } from '../workbook-preserved-metadata.js';
function restoreWorkbookMetadata(args) {
    args.workbook.metadata.preservedWorkbookMetadata = pickPreservedWorkbookMetadata(args.workbookMetadata);
    args.workbookMetadata?.properties?.forEach(({ key, value }) => {
        args.workbook.setWorkbookProperty(key, value);
    });
    if (args.workbookMetadata?.workbookProtection) {
        args.workbook.setWorkbookProtection(args.workbookMetadata.workbookProtection);
    }
    args.workbookMetadata?.macroPayloads?.forEach((payload) => {
        args.workbook.setMacroPayload(payload);
    });
    if (args.workbookMetadata?.calculationSettings) {
        args.workbook.setCalculationSettings(args.workbookMetadata.calculationSettings);
    }
    if (args.workbookMetadata?.volatileContext) {
        args.workbook.setVolatileContext(args.workbookMetadata.volatileContext);
    }
    args.workbookMetadata?.styles?.forEach((style) => {
        args.workbook.upsertCellStyle(style);
    });
    args.workbookMetadata?.formats?.forEach((format) => {
        args.workbook.upsertCellNumberFormat(format);
    });
    if (args.workbookMetadata?.drawingArtifacts) {
        args.workbook.setDrawingArtifacts(args.workbookMetadata.drawingArtifacts);
    }
    if (args.workbookMetadata?.controlArtifacts) {
        args.workbook.metadata.controlArtifacts = structuredClone(args.workbookMetadata.controlArtifacts);
    }
    if (args.workbookMetadata?.externalLinkArtifacts) {
        args.workbook.setExternalLinkArtifacts(args.workbookMetadata.externalLinkArtifacts);
    }
    if (args.workbookMetadata?.threadedCommentArtifacts) {
        args.workbook.setThreadedCommentArtifacts(args.workbookMetadata.threadedCommentArtifacts);
    }
    if (args.workbookMetadata?.cellMetadata) {
        args.workbook.metadata.cellMetadata = structuredClone(args.workbookMetadata.cellMetadata);
    }
}
function restoreSheetMetadata(args) {
    const { workbook, sheet } = args;
    sheet.metadata?.rows?.forEach((entry) => {
        workbook.insertRows(sheet.name, entry.index, 1, [cloneAxisEntry(entry)]);
    });
    sheet.metadata?.columns?.forEach((entry) => {
        workbook.insertColumns(sheet.name, entry.index, 1, [cloneAxisEntry(entry)]);
    });
    restoreAxisMetadata({
        workbook,
        sheetName: sheet.name,
        axis: 'row',
        records: sheet.metadata?.rowMetadata ?? [],
    });
    restoreAxisMetadata({
        workbook,
        sheetName: sheet.name,
        axis: 'column',
        records: sheet.metadata?.columnMetadata ?? [],
    });
    if (sheet.metadata?.sheetFormatPr) {
        workbook.setSheetFormatPr(sheet.name, sheet.metadata.sheetFormatPr);
    }
    if (sheet.metadata?.sheetPr) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.sheetPr = structuredClone(sheet.metadata.sheetPr);
        }
    }
    if (sheet.metadata?.visibility) {
        workbook.setSheetVisibility(sheet.name, sheet.metadata.visibility);
    }
    if (sheet.metadata?.freezePane) {
        workbook.setFreezePane(sheet.name, sheet.metadata.freezePane.rows, sheet.metadata.freezePane.cols, {
            ...(sheet.metadata.freezePane.topLeftCell !== undefined ? { topLeftCell: sheet.metadata.freezePane.topLeftCell } : {}),
            ...(sheet.metadata.freezePane.activePane !== undefined ? { activePane: sheet.metadata.freezePane.activePane } : {}),
        });
    }
    if (sheet.metadata?.tabColor) {
        workbook.setSheetTabColor(sheet.name, structuredClone(sheet.metadata.tabColor));
    }
    if (sheet.metadata?.merges && sheet.metadata.merges.length > 0) {
        workbook.setMergeRanges(sheet.name, sheet.metadata.merges.map((range) => ({ ...range, sheetName: range.sheetName ?? sheet.name })));
    }
    if (sheet.metadata?.sheetProtection) {
        workbook.setSheetProtection(structuredClone(sheet.metadata.sheetProtection));
    }
    if (sheet.metadata?.styleRanges && sheet.metadata.styleRanges.length > 0) {
        workbook.setStyleRanges(sheet.name, sheet.metadata.styleRanges);
    }
    if (sheet.metadata?.formatRanges && sheet.metadata.formatRanges.length > 0) {
        workbook.setFormatRanges(sheet.name, sheet.metadata.formatRanges);
    }
    sheet.metadata?.filters?.forEach((range) => {
        workbook.setFilter(sheet.name, structuredClone(range));
    });
    sheet.metadata?.sorts?.forEach((sort) => {
        workbook.setSort(sheet.name, { ...sort.range }, sort.keys.map((key) => ({ ...key })));
    });
    sheet.metadata?.validations?.forEach((validation) => {
        workbook.setDataValidation(structuredClone(validation));
    });
    sheet.metadata?.conditionalFormats?.forEach((format) => {
        workbook.setConditionalFormat(structuredClone(format));
    });
    if (sheet.metadata?.conditionalFormatArtifacts) {
        workbook.setConditionalFormatArtifacts(sheet.name, structuredClone(sheet.metadata.conditionalFormatArtifacts));
    }
    if (sheet.metadata?.controlArtifacts) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.controlArtifacts = structuredClone(sheet.metadata.controlArtifacts);
        }
    }
    if (sheet.metadata?.drawingArtifacts) {
        workbook.setSheetDrawingArtifacts(sheet.name, sheet.metadata.drawingArtifacts);
    }
    if (sheet.metadata?.threadedCommentArtifacts) {
        workbook.setSheetThreadedCommentArtifacts(sheet.name, sheet.metadata.threadedCommentArtifacts);
    }
    if (sheet.metadata?.legacyCommentVml) {
        workbook.setSheetLegacyCommentVml(sheet.name, sheet.metadata.legacyCommentVml);
    }
    sheet.metadata?.protectedRanges?.forEach((range) => {
        workbook.setRangeProtection(structuredClone(range));
    });
    sheet.metadata?.commentThreads?.forEach((thread) => {
        workbook.setCommentThread(structuredClone(thread));
    });
    sheet.metadata?.notes?.forEach((note) => {
        workbook.setNote(structuredClone(note));
    });
    sheet.metadata?.hyperlinks?.forEach((hyperlink) => {
        workbook.setHyperlink(structuredClone(hyperlink));
    });
    if (sheet.metadata?.arrayFormulas && sheet.metadata.arrayFormulas.formulas.length > 0) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.arrayFormulas = structuredClone(sheet.metadata.arrayFormulas);
        }
    }
    if (sheet.metadata?.dataTableFormulas && sheet.metadata.dataTableFormulas.formulas.length > 0) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.dataTableFormulas = structuredClone(sheet.metadata.dataTableFormulas);
        }
    }
    if (sheet.metadata?.ignoredErrors) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.ignoredErrors = structuredClone(sheet.metadata.ignoredErrors);
        }
    }
    if (sheet.metadata?.printPageSetup) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.printPageSetup = structuredClone(sheet.metadata.printPageSetup);
        }
    }
    if (sheet.metadata?.printerSettings && sheet.metadata.printerSettings.length > 0) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.printerSettings = structuredClone(sheet.metadata.printerSettings);
        }
    }
    if (sheet.metadata?.sparklines) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.sparklines = structuredClone(sheet.metadata.sparklines);
        }
    }
    if (sheet.metadata?.richTextArtifacts && sheet.metadata.richTextArtifacts.cells.length > 0) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.richTextArtifacts = structuredClone(sheet.metadata.richTextArtifacts);
        }
    }
    if (sheet.metadata?.cellMetadataRefs && sheet.metadata.cellMetadataRefs.length > 0) {
        const targetSheet = workbook.getSheet(sheet.name);
        if (targetSheet) {
            targetSheet.cellMetadataRefs = structuredClone(sheet.metadata.cellMetadataRefs);
        }
    }
    const preservedSheetMetadata = pickPreservedSheetMetadata(sheet.metadata);
    if (hasPreservedSheetMetadata(preservedSheetMetadata)) {
        workbook.metadata.preservedSheetMetadata.set(sheet.name, preservedSheetMetadata);
    }
}
function restoreAxisMetadata(args) {
    if (args.records.length === 0) {
        return;
    }
    const sheet = args.workbook.getSheet(args.sheetName);
    if (!sheet) {
        return;
    }
    const entries = args.axis === 'row' ? sheet.rowAxis : sheet.columnAxis;
    for (const record of args.records) {
        if (record.count <= 0) {
            continue;
        }
        if (args.axis === 'row') {
            args.workbook.materializeRowAxisEntries(args.sheetName, record.start, record.count);
        }
        else {
            args.workbook.materializeColumnAxisEntries(args.sheetName, record.start, record.count);
        }
        for (let offset = 0; offset < record.count; offset += 1) {
            const entry = entries[record.start + offset];
            if (entry) {
                applyAxisMetadataRecord(entry, record);
            }
        }
    }
    const bucket = args.axis === 'row' ? args.workbook.metadata.rowMetadata : args.workbook.metadata.columnMetadata;
    syncAxisMetadataBucket(bucket, args.sheetName, entries);
}
function applyAxisMetadataRecord(entry, record) {
    entry.size = record.size ?? null;
    entry.hidden = record.hidden ?? null;
    entry.filterHidden = record.filterHidden ?? null;
    for (const key of axisGeometryKeys) {
        const value = record[key];
        if (value === undefined) {
            delete entry[key];
        }
        else {
            Object.assign(entry, { [key]: value });
        }
    }
}
function cloneAxisEntry(entry) {
    return {
        id: entry.id,
        index: entry.index,
        ...(entry.size !== undefined ? { size: entry.size } : {}),
        ...(entry.hidden !== undefined ? { hidden: entry.hidden } : {}),
        ...(entry.filterHidden !== undefined ? { filterHidden: entry.filterHidden } : {}),
        ...cloneAxisGeometry(entry),
    };
}
function cloneAxisGeometry(entry) {
    return {
        ...(entry.styleIndex !== undefined ? { styleIndex: entry.styleIndex } : {}),
        ...(entry.xlsxWidth !== undefined ? { xlsxWidth: entry.xlsxWidth } : {}),
        ...(entry.xlsxHeight !== undefined ? { xlsxHeight: entry.xlsxHeight } : {}),
        ...(entry.customFormat !== undefined ? { customFormat: entry.customFormat } : {}),
        ...(entry.customWidth !== undefined ? { customWidth: entry.customWidth } : {}),
        ...(entry.bestFit !== undefined ? { bestFit: entry.bestFit } : {}),
        ...(entry.outlineLevel !== undefined ? { outlineLevel: entry.outlineLevel } : {}),
        ...(entry.collapsed !== undefined ? { collapsed: entry.collapsed } : {}),
        ...(entry.customHeight !== undefined ? { customHeight: entry.customHeight } : {}),
        ...(entry.thickTop !== undefined ? { thickTop: entry.thickTop } : {}),
        ...(entry.thickBottom !== undefined ? { thickBottom: entry.thickBottom } : {}),
    };
}
function restoreMetadataStructures(args) {
    args.workbookMetadata?.tables?.forEach((table) => {
        args.workbook.setTable(structuredClone(table));
    });
    args.workbookMetadata?.definedNames?.forEach(({ name, scopeSheetName, value }) => {
        args.workbook.setDefinedName(name, structuredClone(value), scopeSheetName);
    });
    args.workbookMetadata?.spills?.forEach((spill) => {
        args.workbook.setSpill(spill.sheetName, spill.address, spill.rows, spill.cols);
    });
    args.workbookMetadata?.pivots?.forEach((pivot) => {
        args.workbook.setPivot(structuredClone(pivot));
    });
}
export function restoreVisualMetadata(args) {
    args.workbookMetadata?.charts?.forEach((chart) => {
        args.workbook.setChart(structuredClone(chart));
    });
    args.workbookMetadata?.images?.forEach((image) => {
        args.workbook.setImage(structuredClone(image));
    });
    args.workbookMetadata?.shapes?.forEach((shape) => {
        args.workbook.setShape(structuredClone(shape));
    });
}
export function restoreWorkbookStructure(args) {
    args.checkEvaluationBudget?.();
    args.resetWorkbook(args.snapshot.workbook.name);
    restoreWorkbookMetadata({
        workbook: args.workbook,
        workbookMetadata: args.snapshot.workbook.metadata,
    });
    const orderedSheets = [...args.snapshot.sheets].toSorted((left, right) => left.order - right.order);
    orderedSheets.forEach((sheet) => {
        args.checkEvaluationBudget?.();
        args.workbook.createSheet(sheet.name, sheet.order, sheet.id);
    });
    orderedSheets.forEach((sheet) => {
        args.checkEvaluationBudget?.();
        restoreSheetMetadata({ workbook: args.workbook, sheet });
    });
    args.checkEvaluationBudget?.();
    restoreMetadataStructures({
        workbook: args.workbook,
        workbookMetadata: args.snapshot.workbook.metadata,
    });
    return orderedSheets;
}
//# sourceMappingURL=runtime-image-metadata-restore.js.map