import * as i0 from '@angular/core';
import { Injectable } from '@angular/core';
import * as mammoth from 'mammoth';
import { docxToHtml } from '@omer-go/docx-parser-converter-ts';
import * as i1 from '@sd-angular/core/services/notify';

class SdDocxService {
    notifyService;
    #DEFAULT_MAX_SIZE_MB = 50;
    #VALID_EXTENSIONS = ['.doc', '.docx'];
    #ERROR_INVALID_FORMAT = 'Định dạng không hợp lệ. Vui lòng chọn Mẫu có định dạng DOC hoặc DOCX';
    #ERROR_SIZE_EXCEEDED = 'Kích thước tệp mẫu vượt quá tiêu chuẩn hỗ trợ của hệ thống. Vui lòng thử lại';
    #fileInput = null;
    constructor(notifyService) {
        this.notifyService = notifyService;
    }
    async open(options) {
        return new Promise(resolve => {
            this.#createFileInput();
            if (!this.#fileInput) {
                resolve(null);
                return;
            }
            const handleChange = async (event) => {
                const input = event.target;
                const file = input.files?.[0];
                if (!file) {
                    resolve(null);
                    return;
                }
                const result = await this.convertToHtml(file, options);
                resolve(result);
                // Cleanup
                input.value = '';
                input.removeEventListener('change', handleChange);
            };
            this.#fileInput.addEventListener('change', handleChange, { once: true });
            this.#fileInput.click();
        });
    }
    #createFileInput() {
        if (this.#fileInput) {
            return;
        }
        this.#fileInput = document.createElement('input');
        this.#fileInput.type = 'file';
        this.#fileInput.accept = '.doc,.docx';
        this.#fileInput.style.display = 'none';
        document.body.appendChild(this.#fileInput);
    }
    async convertToHtml(input, options) {
        const opts = {
            validateFormat: true,
            validateSize: true,
            maxSizeInMb: this.#DEFAULT_MAX_SIZE_MB,
            ...options,
        };
        try {
            let fileName;
            let fileSize;
            let arrayBuffer;
            if (input instanceof File) {
                fileName = input.name;
                fileSize = input.size;
                arrayBuffer = await this.#fileToArrayBuffer(input);
            }
            else if (input instanceof Blob) {
                fileSize = input.size;
                arrayBuffer = await this.#blobToArrayBuffer(input);
            }
            else {
                arrayBuffer = input;
            }
            if (opts.validateFormat && fileName) {
                if (!this.#isValidFormat(fileName)) {
                    this.notifyService.error(this.#ERROR_INVALID_FORMAT);
                    return null;
                }
            }
            if (opts.validateSize && fileSize !== undefined) {
                const maxSizeInBytes = opts.maxSizeInMb * 1024 * 1024;
                if (fileSize > maxSizeInBytes) {
                    this.notifyService.error(this.#ERROR_SIZE_EXCEEDED);
                    return null;
                }
            }
            const { validateFormat, validateSize, maxSizeInMb, ...conversionOptions } = opts;
            // Try @omer-go first for better formatting, fallback to mammoth on BOM error
            let html;
            let messages = [];
            try {
                html = await docxToHtml(arrayBuffer, {
                    styleMode: 'inline',
                    useSemanticTags: true,
                    fragmentOnly: true,
                    ...conversionOptions,
                });
            }
            catch (omerError) {
                console.log(omerError);
                // Fallback to mammoth if @omer-go fails (e.g., BOM issue)
                console.warn('@omer-go/docx-parser-converter-ts failed, falling back to mammoth:', omerError?.message);
                const result = await mammoth.convertToHtml({ arrayBuffer }, conversionOptions);
                html = result.value;
                messages = result.messages.map(m => m.toString());
            }
            return {
                html,
                messages,
            };
        }
        catch (error) {
            console.error('DocX conversion error:', error);
            this.notifyService.error('Có lỗi xảy ra khi chuyển đổi file DOCX');
            return null;
        }
    }
    async convertToHtmlString(input, options) {
        const result = await this.convertToHtml(input, options);
        return result?.html ?? null;
    }
    #isValidFormat(fileName) {
        const lowerCaseName = fileName.toLowerCase();
        return this.#VALID_EXTENSIONS.some(ext => lowerCaseName.endsWith(ext));
    }
    #fileToArrayBuffer(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => {
                const result = e.target?.result;
                if (result) {
                    resolve(result);
                }
                else {
                    reject(new Error('Failed to read file'));
                }
            };
            reader.onerror = () => reject(reader.error);
            reader.readAsArrayBuffer(file);
        });
    }
    #blobToArrayBuffer(blob) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => {
                const result = e.target?.result;
                if (result) {
                    resolve(result);
                }
                else {
                    reject(new Error('Failed to read blob'));
                }
            };
            reader.onerror = () => reject(reader.error);
            reader.readAsArrayBuffer(blob);
        });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdDocxService, deps: [{ token: i1.SdNotifyService }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdDocxService, providedIn: 'root' });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdDocxService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }], ctorParameters: () => [{ type: i1.SdNotifyService }] });

/**
 * Generated bundle index. Do not edit.
 */

export { SdDocxService };
//# sourceMappingURL=sd-angular-core-services-docx.mjs.map
