import { Host, h, Fragment, } from "@stencil/core";
import i18next from "i18next";
import authStore from "../../services/auth";
import printStore, { EzpPrintService } from "../../services/print";
import userStore, { EzpUserService } from "../../services/user";
import { managePaperDimensions, poll, removeEmptyStrings } from "../../utils/utils";
import { PAPER_ID, validatePageRange, formatPageRange } from "../../utils/utils";
export class EzpPrinterSelection {
    constructor() {
        this.fileExtension = '';
        this.duplexOptions = [
            {
                id: 1,
                title: i18next.t('printer_selection.duplex_none'),
            },
            {
                id: 2,
                title: i18next.t('printer_selection.duplex_long'),
            },
            {
                id: 3,
                title: i18next.t('printer_selection.duplex_short'),
            },
        ];
        this.ColorOptions = [
            {
                id: 1,
                title: i18next.t('printer_selection.color_color'),
            },
            {
                id: 2,
                title: i18next.t('printer_selection.color_grayscale'),
            },
        ];
        this.hidemenu = false;
        this.hideheader = false;
        /**
         *
         * States
         *
         */
        this.loading = true;
        this.printProcessing = false;
        this.pageRangeInvalid = false;
        this.uploading = false;
        this.preparingUpload = false;
        this.printSuccess = false;
        this.printFailed = false;
        this.notSupported = false;
        this.noPrinters = false;
        this.hubDriverError = false;
        this.userMenuOpen = false;
        this.printStopped = false;
        this.selectedPrinterConfig = {
            Default: {
                Color: '',
                Duplex: '',
                Paper: '',
                Orientation: '',
                Resolution: '',
                Tray: '',
            },
            OrientationsSupported: [],
            PaperFormats: [],
            Resolutions: [],
            DuplexSupported: false,
            Color: false,
            Trays: [],
        };
        // needs to be initialised with empty strings
        this.selectedProperties = {
            paper: '',
            paperid: '',
            color: false,
            duplex: true,
            duplexmode: 1,
            orientation: 1,
            copies: '',
            resolution: 0,
            paperlength: 0,
            paperwidth: 0,
            defaultSource: '',
            trayname: '',
            PageRanges: '',
        };
        this.currentFileIndex = 0;
        this.totalFiles = 0;
        this.failedFiles = [];
        this.successfulFiles = [];
        this.partialSuccess = false;
        /**
         *
         * Private methods
         *
         */
        /** Description... */
        this.handleCancel = () => {
            this.failedFiles = [];
            this.successfulFiles = [];
            this.partialSuccess = false;
            this.hubDriverError = false;
            this.printCancel.emit();
        };
        this.validateData = (data) => {
            console.log('[validateData] Checking data:', data);
            const { jobstatus } = data;
            // Define status handlers
            const statusHandlers = {
                0: () => {
                    // Success
                    this.printSuccess = true;
                    this.printProcessing = false;
                    return true;
                },
                1246: () => false, // Still processing
                129: () => false, // Still processing
                3011: () => {
                    // Failure
                    this.printFailed = true;
                    this.printProcessing = false;
                    return true;
                },
                2: () => {
                    // Failure
                    this.printFailed = true;
                    this.printProcessing = false;
                    return true;
                },
            };
            // Check for hub printer driver errors
            const hubDriverErrorCodes = [412, 500, 503, 1048579];
            if (hubDriverErrorCodes.includes(jobstatus) && this.selectedPrinter.is_queue) {
                this.hubDriverError = true;
                this.printProcessing = false;
                return true;
            }
            // Use handler if exists, otherwise treat as failure
            const handler = statusHandlers[jobstatus];
            if (handler) {
                return handler();
            }
            // Unknown status, treat as failure for safety
            this.printFailed = true;
            this.printProcessing = false;
            return true;
        };
        this.POLL_INTERVAL = 2000;
        this.MAX_POLL_ATTEMPTS = Infinity;
        this.HUB_TIMEOUT = 30000; // 30 seconds timeout for hub printers
        /** Description... */
        this.handlePrint = async () => {
            this.printButton.blur();
            this.printProcessing = true;
            this.failedFiles = [];
            this.successfulFiles = [];
            this.partialSuccess = false;
            this.hubDriverError = false;
            // Set up timeout for hub printers to prevent infinite loading
            let hubTimeout;
            if (this.selectedPrinter.is_queue) {
                hubTimeout = setTimeout(() => {
                    console.log('[handlePrint] Hub printer timeout reached, setting driver error');
                    this.hubDriverError = true;
                    this.printProcessing = false;
                }, this.HUB_TIMEOUT);
            }
            // we have to initialse this obj with empty strings to display the select component
            // but don't want to send any attributes with empty strings to the API
            if (this.selectedPrinterConfig.Trays &&
                this.selectedPrinterConfig.Trays.length >= 0 &&
                this.selectedPrinterConfig.Trays[0] == null) {
                delete this.selectedProperties.trayname;
                delete this.selectedProperties.defaultSource;
            }
            let cleanPrintProperties = removeEmptyStrings(this.selectedProperties);
            cleanPrintProperties = managePaperDimensions(cleanPrintProperties);
            if (cleanPrintProperties.PageRanges)
                cleanPrintProperties.PageRanges = formatPageRange(cleanPrintProperties.PageRanges);
            // put it in store for further use
            printStore.state.fileUrl = this.fileurl;
            printStore.state.fileID = this.fileid;
            printStore.state.fileType = this.filetype;
            printStore.state.printerID = this.selectedPrinter.id;
            printStore.state.printerProperties = this.selectedProperties;
            printStore.state.fileName = this.filename;
            if (this.fileurl) {
                this.printService
                    .printFileByUrl(authStore.state.accessToken, this.fileurl, this.filetype, this.selectedPrinter.id, cleanPrintProperties, this.filename)
                    .then((response) => {
                    if (response.status === 200 && this.selectedPrinter.is_queue) {
                        this.printProcessing = false;
                        this.printSuccess = true;
                        if (hubTimeout)
                            clearTimeout(hubTimeout);
                    }
                    if (response.status === 412) {
                        response.json().then((data) => (this.fileid = data.fileid));
                        this.printService.printByFileID(authStore.state.accessToken, this.fileid, this.filetype, this.selectedPrinter.id, cleanPrintProperties, this.filename);
                    }
                    else {
                        return response.json();
                    }
                })
                    .then((data) => {
                    if (data.code === 804) {
                        this.printFailed = true;
                        this.printProcessing = false;
                        if (hubTimeout)
                            clearTimeout(hubTimeout);
                    }
                    else if (this.selectedPrinter.is_queue &&
                        (data.code === 412 || data.code === 500 || data.code === 503 || data.code === 1048579)) {
                        // Hub printer specific errors - likely driver not assigned
                        console.log('[handlePrint] Hub printer driver error detected:', data);
                        this.hubDriverError = true;
                        this.printProcessing = false;
                        if (hubTimeout)
                            clearTimeout(hubTimeout);
                    }
                    else if (data.jobid) {
                        printStore.state.jobID = data.jobid;
                        poll({
                            fn: this.printService.getPrintStatus,
                            validate: this.validateData,
                            interval: this.POLL_INTERVAL,
                            maxAttempts: this.MAX_POLL_ATTEMPTS,
                        }).catch((err) => {
                            console.warn('[handlePrint] Polling error:', err);
                            // Check if this is a hub printer and the error might be driver-related
                            if (this.selectedPrinter.is_queue) {
                                this.hubDriverError = true;
                            }
                            else {
                                this.printFailed = true;
                            }
                            this.printProcessing = false;
                            if (hubTimeout)
                                clearTimeout(hubTimeout);
                        });
                    }
                    else {
                        // No job ID returned - check if it's a hub printer
                        if (this.selectedPrinter.is_queue) {
                            this.hubDriverError = true;
                        }
                        else {
                            this.printFailed = true;
                        }
                        this.printProcessing = false;
                        if (hubTimeout)
                            clearTimeout(hubTimeout);
                    }
                })
                    .catch((error) => {
                    console.log('[handlePrint] Error caught:', error);
                    // Check if this is a hub printer and the error might be driver-related
                    if (this.selectedPrinter.is_queue) {
                        this.hubDriverError = true;
                    }
                    else {
                        this.printFailed = true;
                    }
                    this.printProcessing = false;
                    if (hubTimeout)
                        clearTimeout(hubTimeout);
                });
            }
            else if (this.files && this.files.length > 1) {
                await this.processMultipleFiles(this.files, cleanPrintProperties);
                if (hubTimeout)
                    clearTimeout(hubTimeout);
            }
            else if (this.files && this.files.length === 1) {
                // --- Begin: Consistent single file handling ---
                this.totalFiles = 1;
                this.currentFileIndex = 0;
                this.failedFiles = [];
                this.successfulFiles = [];
                try {
                    await this.processSingleFile(this.files[0], cleanPrintProperties);
                    this.successfulFiles.push(this.files[0].name);
                    this.printSuccess = true;
                    this.partialSuccess = false;
                    this.printProcessing = false;
                }
                catch (error) {
                    console.error(`Error processing file ${this.files[0].name}:`, error);
                    this.failedFiles.push(this.files[0].name);
                    this.printFailed = true;
                    this.partialSuccess = false;
                    this.printProcessing = false;
                    // Check if this is a hub driver error
                    if (error.message && error.message.includes('Hub printer driver error')) {
                        this.hubDriverError = true;
                    }
                }
                if (hubTimeout)
                    clearTimeout(hubTimeout);
                // --- End: Consistent single file handling ---
            }
            localStorage.setItem('properties', JSON.stringify(this.selectedProperties));
            localStorage.setItem('printer', JSON.stringify(this.selectedPrinter));
            this.printStopped = false;
        };
        this.handleUserMenu = () => {
            this.userMenuOpen = true;
        };
        this.validateFileType = async (name) => {
            const extension = name.split('.').pop();
            this.fileExtension = extension.toLowerCase();
            return printStore.state.supportedFileExtensions.includes(`${this.fileExtension}`);
        };
    }
    /**
     *
     * Listeners
     *
     */
    listenInputValueChanged(event) {
        this.setSelectedProperties(event.detail);
    }
    listenSelectSelection(event) {
        this.setSelectedProperties(event.detail);
    }
    listenStepperChanged(event) {
        this.selectedProperties.copies = event.detail;
    }
    listenUserMenuClosure() {
        this.userMenuOpen = false;
    }
    listenLogout() {
        this.printCancel.emit();
        this.logout.emit();
    }
    listenStatusCancel(event) {
        if (event.detail === 'print-processing') {
            this.printStopped = true;
            this.printProcessing = false;
            // Abort the print request
            this.printService.abortPrint();
        }
    }
    listenStatusClose(event) {
        switch (event.detail) {
            case 'print-success':
                this.printSuccess = false;
                this.partialSuccess = false;
                this.failedFiles = [];
                this.successfulFiles = [];
                this.printCancel.emit();
                break;
            case 'print-failed':
                this.printFailed = false;
                break;
            case 'hub-driver-error':
                this.hubDriverError = false;
                break;
            case 'not-supported':
                this.noPrinters = false;
                break;
            case 'no-printers':
                this.noPrinters = false;
                this.printCancel.emit();
                break;
        }
    }
    listenStatusRetry(event) {
        switch (event.detail) {
            case 'not-supported':
                this.printCancel.emit();
                break;
            case 'print-failed':
                this.printFailed = false;
                this.printProcessing = false;
                this.handlePrint();
                break;
            case 'hub-driver-error':
                this.hubDriverError = false;
                this.printProcessing = false;
                this.handlePrint();
                break;
        }
    }
    getPropertiesFromLocalStorage() {
        if (localStorage.getItem('properties')) {
            this.selectedProperties = JSON.parse(localStorage.getItem('properties'));
        }
        if (localStorage.getItem('printer')) {
            const savedPrinter = JSON.parse(localStorage.getItem('printer'));
            if (this.printers.some((printer) => printer.id === savedPrinter.id)) {
                this.selectedPrinter = savedPrinter;
            }
            else {
                this.selectedPrinter = { id: '', location: '', name: '', is_queue: false };
                localStorage.removeItem('printer');
                localStorage.removeItem('properties');
            }
        }
        else {
            this.selectedPrinter = { id: '', location: '', name: '', is_queue: false };
        }
        this.setPaperid();
    }
    setPaperid() {
        this.paperid = this.selectedProperties.paperid;
    }
    getUserInfo() {
        const userService = new EzpUserService();
        return userService.getUserInfo().then((user) => {
            userStore.state.user = user;
            this.userName = userStore.state.user.display_name;
        });
    }
    async setSelectedProperties(eventDetails) {
        switch (eventDetails.type) {
            case 'printer':
                this.selectedPrinter.id = eventDetails.id;
                this.selectedPrinter.name = eventDetails.title;
                this.selectedPrinter.is_queue = eventDetails.is_queue;
                await this.printService
                    .getPrinterProperties(authStore.state.accessToken, this.selectedPrinter.id)
                    .then((data) => {
                    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
                    this.selectedPrinterConfig = Object.assign(Object.assign({}, this.selectedPrinterConfig), data[0]);
                    this.selectedProperties.color =
                        ((_a = this.selectedPrinterConfig.Default) === null || _a === void 0 ? void 0 : _a.Color) == 'color' ? true : false;
                    const defaultOrientation = (_b = this.selectedPrinterConfig.Default) === null || _b === void 0 ? void 0 : _b.Orientation;
                    const defaultOrientationIndex = (_c = this.selectedPrinterConfig.Default) === null || _c === void 0 ? void 0 : _c.OrientationIndex;
                    let orientationFallback;
                    if (defaultOrientation) {
                        const idx = (_d = this.selectedPrinterConfig.OrientationsSupported) === null || _d === void 0 ? void 0 : _d.indexOf(defaultOrientation);
                        if (typeof idx === 'number' && idx >= 0)
                            orientationFallback = idx + 1;
                    }
                    this.selectedProperties.orientation = defaultOrientationIndex !== null && defaultOrientationIndex !== void 0 ? defaultOrientationIndex : orientationFallback;
                    this.selectedProperties.resolution = (_e = this.selectedPrinterConfig.Default) === null || _e === void 0 ? void 0 : _e.Resolution;
                    let defaultPaper = (_f = this.selectedPrinterConfig.PaperFormats) === null || _f === void 0 ? void 0 : _f.find((obj) => obj.Default === true);
                    this.selectedProperties.paper = defaultPaper === null || defaultPaper === void 0 ? void 0 : defaultPaper.Name;
                    this.selectedProperties.paperid = defaultPaper === null || defaultPaper === void 0 ? void 0 : defaultPaper.Id;
                    let defaultSource = (_g = this.selectedPrinterConfig.Trays) === null || _g === void 0 ? void 0 : _g.find((obj) => obj.Default === true);
                    if (this.selectedPrinterConfig.Trays &&
                        this.selectedPrinterConfig.Trays.length >= 1 &&
                        this.selectedPrinterConfig.Trays[0] != null) {
                        this.selectedProperties.trayname = defaultSource === null || defaultSource === void 0 ? void 0 : defaultSource.Name;
                        this.selectedProperties.defaultSource = defaultSource === null || defaultSource === void 0 ? void 0 : defaultSource.Index;
                    }
                    if (this.selectedPrinterConfig.Trays &&
                        this.selectedPrinterConfig.Trays.length >= 0 &&
                        this.selectedPrinterConfig.Trays[0] == null) {
                        delete this.selectedProperties.trayname;
                        delete this.selectedProperties.defaultSource;
                    }
                    this.selectedProperties.duplex = (_h = this.selectedPrinterConfig) === null || _h === void 0 ? void 0 : _h.DuplexSupported;
                    this.selectedProperties.duplexmode = (_j = this.selectedPrinterConfig) === null || _j === void 0 ? void 0 : _j.DuplexMode;
                    delete this.selectedProperties.PageRanges;
                });
                // this.setDefaultPaperFormat()
                break;
            case 'color':
                this.selectedProperties.color =
                    eventDetails.title == i18next.t('printer_selection.color_color') ? true : false;
                break;
            case 'orientation':
                this.selectedProperties.orientation = eventDetails.id;
                break;
            case 'format':
                this.selectedProperties.paper = eventDetails.title;
                this.selectedProperties.paperid = eventDetails.id;
                break;
            case 'quality':
                this.selectedProperties.resolution = eventDetails.title;
                break;
            case 'length':
                this.selectedProperties.paperlength = eventDetails.value;
                break;
            case 'width':
                this.selectedProperties.paperwidth = eventDetails.value;
                break;
            case 'tray':
                if (this.selectedPrinterConfig.Trays &&
                    this.selectedPrinterConfig.Trays.length >= 0 &&
                    this.selectedPrinterConfig.Trays[0] == null) {
                    delete this.selectedProperties.trayname;
                    delete this.selectedProperties.defaultSource;
                }
                if (this.selectedPrinterConfig.Trays &&
                    this.selectedPrinterConfig.Trays.length >= 1 &&
                    this.selectedPrinterConfig.Trays[0] != null) {
                    this.selectedProperties.trayname = eventDetails.title;
                    this.selectedProperties.defaultSource = eventDetails.id;
                }
                break;
            case 'paper_ranges':
                this.selectedProperties.PageRanges = eventDetails.value;
                this.pageRangeInvalid = !validatePageRange(this.selectedProperties.PageRanges);
                break;
            case 'duplex':
                if (eventDetails.title == i18next.t('printer_selection.duplex_none') ||
                    eventDetails.title == i18next.t('printer_selection.duplex_long') ||
                    eventDetails.title == i18next.t('printer_selection.duplex_short')) {
                    this.selectedProperties.duplex = true;
                }
                else {
                    this.selectedProperties.duplex = false;
                }
                this.selectedProperties.duplexmode = eventDetails.id;
                break;
            default:
                break;
        }
        this.setPaperid();
    }
    async handleFiles(files, printPorperties) {
        this.totalFiles = files.length;
        this.currentFileIndex = 0;
        this.failedFiles = [];
        this.successfulFiles = [];
        // Process each file individually
        for (let i = 0; i < files.length; i++) {
            this.currentFileIndex = i;
            const file = files[i];
            try {
                await this.processSingleFile(file, printPorperties);
                this.successfulFiles.push(file.name);
            }
            catch (error) {
                console.error(`Error processing file ${file.name}:`, error);
                this.failedFiles.push(file.name);
                // Check if this is a hub driver error
                if (error.message && error.message.includes('Hub printer driver error')) {
                    this.hubDriverError = true;
                    this.printProcessing = false;
                    return; // Stop processing other files if it's a hub driver issue
                }
                // Continue with the next file
            }
        }
        // Determine final status based on results
        if (this.failedFiles.length === 0) {
            // All files processed successfully
            this.printSuccess = true;
            this.partialSuccess = false;
            this.printProcessing = false;
        }
        else if (this.successfulFiles.length === 0) {
            // All files failed
            this.printFailed = true;
            this.partialSuccess = false;
            this.printProcessing = false;
        }
        else {
            // Some files succeeded, some failed - show partial success
            this.printSuccess = true;
            this.partialSuccess = true;
            this.printProcessing = false;
        }
    }
    async processSingleFile(file, printProperties) {
        this.preparingUpload = true;
        const response = await this.printService.prepareFileUpload(authStore.state.accessToken);
        this.preparingUpload = false;
        const fileid = response.fileid;
        const sasUri = response.sasUri;
        const filetype = this.getFileExtension(file.name);
        this.uploading = true;
        try {
            // Upload the file
            const res = await this.printService.uploadBlobFiles(sasUri, file);
            if (res._response.status === 201) {
                // Print the file
                const data = await this.printService.printByFileID(authStore.state.accessToken, fileid, filetype, this.selectedPrinter.id, printProperties, file.name);
                if (data.code === 804) {
                    throw new Error(`Print failed for file: ${file.name}`);
                }
                // Check for hub printer driver errors
                if (this.selectedPrinter.is_queue &&
                    (data.code === 412 || data.code === 500 || data.code === 503)) {
                    throw new Error(`Hub printer driver error for file: ${file.name}`);
                }
                if (data.jobid) {
                    printStore.state.jobID = data.jobid;
                    // Wait for this print job to complete before processing the next file
                    await this.waitForPrintCompletion();
                }
                else {
                    throw new Error(`No job ID returned for file: ${file.name}`);
                }
            }
            else {
                throw new Error(`Upload failed for file: ${file.name}`);
            }
        }
        catch (error) {
            this.uploading = false;
            throw error;
        }
        this.uploading = false;
    }
    async waitForPrintCompletion() {
        while (true) {
            try {
                const data = await this.printService.getPrintStatus();
                console.log('[waitForPrintCompletion] Poll response:', data);
                if (data.jobstatus === 0) {
                    // Success
                    return;
                }
                else if (data.jobstatus === 1246 || data.jobstatus === 129) {
                    // Still processing, wait before next poll
                    await new Promise((resolve) => setTimeout(resolve, this.POLL_INTERVAL));
                }
                else if (data.jobstatus === 3011 || data.jobstatus === 2) {
                    // Failure
                    throw new Error('Print job failed: ' + (data.jobstatusstring || data.jobstatus));
                }
                else if (this.selectedPrinter.is_queue &&
                    (data.jobstatus === 412 || data.jobstatus === 500 || data.jobstatus === 503)) {
                    // Hub printer driver error
                    throw new Error('Hub printer driver error: ' + (data.jobstatusstring || data.jobstatus));
                }
                else {
                    // Unknown status, treat as failure for safety
                    throw new Error('Unknown print job status: ' + data.jobstatus);
                }
            }
            catch (error) {
                throw error;
            }
        }
    }
    getFileExtension(filename) {
        const extension = filename.split('.').pop();
        return extension ? extension.toLowerCase() : '';
    }
    setDefaultPaperFormat() {
        var _a, _b, _c, _d, _e;
        let format;
        const language = navigator.language;
        if (language === 'en-US') {
            format = 'Letter';
        }
        else if (language === 'my') {
            format = 'Letter';
        }
        else {
            format = 'A4';
        }
        if ((_a = this.selectedPrinterConfig.PaperFormats) === null || _a === void 0 ? void 0 : _a.find((el) => el.Name.includes(format))) {
            this.selectedProperties.paper = (_b = this.selectedPrinterConfig.PaperFormats) === null || _b === void 0 ? void 0 : _b.find((el) => el.Name.includes(format)).Name;
            this.selectedProperties.paperid = (_c = this.selectedPrinterConfig.PaperFormats) === null || _c === void 0 ? void 0 : _c.find((el) => el.Name.includes(format)).Id;
        }
        else {
            this.selectedProperties.paper = (_d = this.selectedPrinterConfig.PaperFormats[0]) === null || _d === void 0 ? void 0 : _d.Name;
            this.selectedProperties.paperid = (_e = this.selectedPrinterConfig.PaperFormats[0]) === null || _e === void 0 ? void 0 : _e.Id;
        }
        this.setPaperid();
    }
    async processMultipleFiles(files, printProperties) {
        this.totalFiles = files.length;
        this.currentFileIndex = 0;
        this.failedFiles = [];
        this.successfulFiles = [];
        for (let i = 0; i < files.length; i++) {
            this.currentFileIndex = i;
            const file = files[i];
            try {
                await this.processSingleFile(file, printProperties);
                this.successfulFiles.push(file.name);
            }
            catch (error) {
                console.error(`Error processing file ${file.name}:`, error);
                this.failedFiles.push(file.name);
                // Continue with the next file
            }
        }
        // Set UI state
        if (this.failedFiles.length === 0) {
            this.printSuccess = true;
            this.partialSuccess = false;
            this.printProcessing = false;
        }
        else if (this.successfulFiles.length === 0) {
            this.printFailed = true;
            this.partialSuccess = false;
            this.printProcessing = false;
        }
        else {
            this.printSuccess = true;
            this.partialSuccess = true;
            this.printProcessing = false;
        }
    }
    /**
     *
     * Lifecycle methods
     *
     */
    /** Description... */
    async connectedCallback() {
        this.printService = new EzpPrintService(this.redirectURI, this.clientID);
        this.printService.registerFetchInterceptor();
        await this.getUserInfo();
        await this.printService
            .getPrinterList(authStore.state.accessToken)
            .then((printers) => {
            this.printers = printers;
            if (!(this.printers.length > 0)) {
                this.noPrinters = true;
            }
        });
        this.getPropertiesFromLocalStorage();
        // if printer is stored from previous print, get the config to enable property selection
        if (this.selectedPrinter.id != '') {
            await this.printService
                .getPrinterProperties(authStore.state.accessToken, this.selectedPrinter.id)
                .then((data) => {
                var _a, _b, _c, _d, _e, _f, _g, _h, _j;
                this.selectedPrinterConfig = data[0];
                this.selectedProperties.color =
                    ((_a = this.selectedPrinterConfig.Default) === null || _a === void 0 ? void 0 : _a.Color) == 'color' ? true : false;
                const defaultOrientation = (_b = this.selectedPrinterConfig.Default) === null || _b === void 0 ? void 0 : _b.Orientation;
                const defaultOrientationIndex = (_c = this.selectedPrinterConfig.Default) === null || _c === void 0 ? void 0 : _c.OrientationIndex;
                let orientationFallback;
                if (defaultOrientation) {
                    const idx = (_d = this.selectedPrinterConfig.OrientationsSupported) === null || _d === void 0 ? void 0 : _d.indexOf(defaultOrientation);
                    if (typeof idx === 'number' && idx >= 0)
                        orientationFallback = idx + 1;
                }
                this.selectedProperties.orientation = defaultOrientationIndex !== null && defaultOrientationIndex !== void 0 ? defaultOrientationIndex : orientationFallback;
                this.selectedProperties.resolution = (_e = this.selectedPrinterConfig.Default) === null || _e === void 0 ? void 0 : _e.Resolution;
                let defaultPaper = (_f = this.selectedPrinterConfig.PaperFormats) === null || _f === void 0 ? void 0 : _f.find((obj) => obj.Default === true);
                this.selectedProperties.paper = defaultPaper === null || defaultPaper === void 0 ? void 0 : defaultPaper.Name;
                this.selectedProperties.paperid = defaultPaper === null || defaultPaper === void 0 ? void 0 : defaultPaper.Id;
                let defaultSource = (_g = this.selectedPrinterConfig.Trays) === null || _g === void 0 ? void 0 : _g.find((obj) => obj.Default === true);
                if (this.selectedPrinterConfig.Trays &&
                    this.selectedPrinterConfig.Trays.length >= 1 &&
                    this.selectedPrinterConfig.Trays[0] != null) {
                    this.selectedProperties.trayname = defaultSource === null || defaultSource === void 0 ? void 0 : defaultSource.Name;
                    this.selectedProperties.defaultSource = defaultSource === null || defaultSource === void 0 ? void 0 : defaultSource.Index;
                }
                if (this.selectedPrinterConfig.Trays &&
                    this.selectedPrinterConfig.Trays.length >= 0 &&
                    this.selectedPrinterConfig.Trays[0] == null) {
                    delete this.selectedProperties.trayname;
                    delete this.selectedProperties.defaultSource;
                }
                this.selectedProperties.duplex = (_h = this.selectedPrinterConfig) === null || _h === void 0 ? void 0 : _h.DuplexSupported;
                this.selectedProperties.duplexmode = (_j = this.selectedPrinterConfig) === null || _j === void 0 ? void 0 : _j.DuplexMode;
                delete this.selectedProperties.PageRanges;
            });
            if (this.selectedProperties.paper === '') {
                this.setDefaultPaperFormat();
            }
        }
        await (await this.printService.getConfig(authStore.state.accessToken))
            .json()
            .then((response) => {
            printStore.state.supportedFileExtensions = response.System.FILEEXT;
        });
        await this.printService
            .getAllPrinterProperties(authStore.state.accessToken)
            .then((printerConfig) => {
            this.printerConfig = printerConfig;
        });
        if (this.files && this.files.length > 0) {
            // Validate all files
            const validationPromises = this.files.map((file) => this.validateFileType(file.name));
            const validationResults = await Promise.all(validationPromises);
            const allValid = validationResults.every((valid) => valid);
            this.notSupported = !allValid;
        }
        this.loading = false;
    }
    /**
     *
     * Render method
     *
     */
    render() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
        return this.loading ? (h("ezp-status", { processing: true, description: i18next.t('printer_selection.loading'), instance: "loading" })) : (h(Host, { class: { seamless: this.seamless } }, h("div", { id: "box", "data-backdrop-surface": true }, !this.printStopped && (h(Fragment, null, this.printProcessing ? (h("ezp-status", { processing: true, description: this.totalFiles > 1
                ? `${i18next.t('printer_selection.print_processing')} (${this.currentFileIndex + 1}/${this.totalFiles})`
                : this.preparingUpload
                    ? i18next.t('printer_selection.prepare_upload')
                    : this.uploading
                        ? i18next.t('printer_selection.uploading')
                        : i18next.t('printer_selection.print_processing'), instance: "print-processing", cancel: true })) : this.selectedPrinter.is_queue && this.printSuccess ? (h("ezp-status", { icon: "checkmark-alt", description: this.totalFiles > 1
                ? this.failedFiles.length > 0
                    ? `${i18next.t('printer_selection.pull_print_success')} (${this.successfulFiles.length}/${this.totalFiles} files)`
                    : `${i18next.t('printer_selection.pull_print_success')} (${this.totalFiles} files)`
                : i18next.t('printer_selection.pull_print_success'), instance: "print-success", close: true })) : this.printSuccess ? (h("ezp-status", { icon: this.partialSuccess ? 'exclamation-mark' : 'checkmark-alt', description: this.totalFiles > 1
                ? this.partialSuccess
                    ? `${i18next.t('printer_selection.print_success')} (${this.successfulFiles.length}/${this.totalFiles} ${i18next.t('printer_selection.files')} - ${this.failedFiles.length} failed`
                    : `${i18next.t('printer_selection.print_success')} (${this.totalFiles} ${i18next.t('printer_selection.files')})`
                : i18next.t('printer_selection.print_success'), instance: "print-success", close: true })) : this.printFailed ? (h("ezp-status", { icon: "exclamation-mark", description: i18next.t('printer_selection.print_failed'), instance: "print-failed", close: true, retry: true })) : this.notSupported ? (h("ezp-status", { icon: "exclamation-mark", description: i18next.t('printer_selection.not_supported'), instance: "not-supported", retry: true })) : this.hubDriverError ? (h("ezp-status", { icon: "exclamation-mark", description: i18next.t('printer_selection.print_failed'), instance: "hub-driver-error", close: true, retry: true })) : this.noPrinters ? (h("ezp-status", { icon: "exclamation-mark", description: i18next.t('printer_selection.no_printers'), instance: "no-printers", close: true })) : null)), !this.hideheader && (h("div", { id: "header" }, h("ezp-label", { weight: "heavy", text: i18next.t('printer_selection.print') + `${!this.notSupported ? ':' : ''}` }), h("ezp-label", { text: !this.notSupported
                ? this.files && this.files.length > 1
                    ? i18next.t('printer_selection.files_selected', { count: this.files.length })
                    : this.filename
                : '', ellipsis: true }), !this.hidemenu && (h("ezp-icon-button", { level: "tertiary", icon: "menu", id: "toggle-menu", type: "button", onClick: this.handleUserMenu })))), h("div", { id: "body" }, h("div", { id: "printer" }, h("ezp-select", { label: i18next.t('printer_selection.printer'), icon: "printer", placeholder: this.printers.length > 0
                ? i18next.t('printer_selection.select_printer')
                : i18next.t('printer_selection.no_printers'), toggleFlow: "vertical", optionFlow: "vertical", options: this.printers.map((printer) => ({
                id: printer.id,
                title: printer.name,
                meta: printer.location !== '' ? printer.location : '',
                type: 'printer',
                is_queue: printer.is_queue,
            })), preSelected: this.selectedPrinter.id ? this.selectedPrinter.name : null, disabled: !(this.printers.length > 0) })), h("div", { id: "options" }, h("ezp-select", { label: i18next.t('printer_selection.color'), icon: "color", placeholder: i18next.t('printer_selection.select_color'), toggleFlow: "horizontal", options: (_a = this.ColorOptions) === null || _a === void 0 ? void 0 : _a.map((option) => ({
                id: option.id,
                title: option.title,
                meta: '',
                type: 'color',
            })), preSelected: this.selectedPrinter.id && ((_b = this.selectedPrinterConfig.Default) === null || _b === void 0 ? void 0 : _b.Color) == 'color'
                ? i18next.t('printer_selection.color_color')
                : i18next.t('printer_selection.color_grayscale'), disabled: !this.selectedPrinterConfig.ColorSupported }), h("ezp-select", { label: i18next.t('printer_selection.duplex'), icon: "duplex", placeholder: i18next.t('printer_selection.select_duplex'), toggleFlow: "horizontal", options: (_c = this.duplexOptions) === null || _c === void 0 ? void 0 : _c.map((option) => ({
                id: option.id,
                title: option.title,
                meta: '',
                type: 'duplex',
            })), preSelected: this.selectedPrinter.id &&
                ((_d = this.selectedPrinterConfig.Default) === null || _d === void 0 ? void 0 : _d.Duplex) == 'duplex_simplex'
                ? i18next.t('printer_selection.duplex_none')
                : ((_e = this.selectedPrinterConfig.Default) === null || _e === void 0 ? void 0 : _e.Duplex) == 'duplex_vertical'
                    ? i18next.t('printer_selection.duplex_long')
                    : ((_f = this.selectedPrinterConfig.Default) === null || _f === void 0 ? void 0 : _f.Duplex) == 'duplex_horizontal'
                        ? i18next.t('printer_selection.duplex_short')
                        : null, disabled: !this.selectedPrinterConfig.DuplexSupported }), h("ezp-select", { label: i18next.t('printer_selection.size'), icon: "size", placeholder: i18next.t('printer_selection.select_size'), toggleFlow: "horizontal", optionFlow: "horizontal", options: this.selectedPrinterConfig.PaperFormats &&
                this.selectedPrinterConfig.PaperFormats.map((format) => ({
                    id: format.Id,
                    title: format.Name,
                    meta: `${format.XRes} x ${format.YRes}`,
                    type: 'format',
                })), preSelected: this.selectedPrinter.id &&
                ((_g = this.selectedPrinterConfig.PaperFormats) === null || _g === void 0 ? void 0 : _g.find((el) => { var _a; return el.Name.includes((_a = this.selectedPrinterConfig.Default) === null || _a === void 0 ? void 0 : _a.Paper); }))
                ? (_h = this.selectedPrinterConfig.Default) === null || _h === void 0 ? void 0 : _h.Paper
                : null, disabled: !(((_j = this.selectedPrinterConfig.PaperFormats) === null || _j === void 0 ? void 0 : _j.length) > 0) }), this.paperid == PAPER_ID ? (h(Fragment, null, h("ezp-input", { icon: "width", suffix: "mm", value: this.selectedProperties.paperwidth, eventType: "width", type: "number", label: i18next.t('printer_selection.width') }), h("ezp-input", { icon: "height", suffix: "mm", value: this.selectedProperties.paperlength, eventType: "length", type: "number", label: i18next.t('printer_selection.length') }))) : null, h("ezp-select", { label: i18next.t('printer_selection.orientation'), icon: "orientation", placeholder: i18next.t('printer_selection.select_orientation'), toggleFlow: "horizontal", options: this.selectedPrinterConfig.OrientationsSupported.map((orientation, index) => ({
                id: index + 1,
                title: i18next.t(`printer_selection.orientation_${orientation}`),
                meta: '',
                type: 'orientation',
            })), preSelected: this.selectedPrinter.id ? this.selectedProperties.orientation : null, disabled: !(this.selectedPrinterConfig.OrientationsSupported.length > 0) }), h("ezp-select", { label: i18next.t('printer_selection.quality'), icon: "quality", placeholder: i18next.t('printer_selection.select_quality'), toggleFlow: "horizontal", options: (_k = this.selectedPrinterConfig.Resolutions) === null || _k === void 0 ? void 0 : _k.map((option, index) => ({
                id: index,
                title: option,
                meta: '',
                type: 'quality',
            })), preSelected: this.selectedPrinter.id &&
                ((_l = this.selectedPrinterConfig.Resolutions) === null || _l === void 0 ? void 0 : _l.includes(this.selectedPrinterConfig.Default.Resolution))
                ? this.selectedPrinterConfig.Default.Resolution
                : null, disabled: !(((_m = this.selectedPrinterConfig.Resolutions) === null || _m === void 0 ? void 0 : _m.length) > 0) }), this.selectedPrinterConfig.Trays &&
            this.selectedPrinterConfig.Trays.length >= 1 &&
            this.selectedPrinterConfig.Trays[0] != null ? (h("ezp-select", { label: i18next.t('printer_selection.trays'), icon: "trays", placeholder: i18next.t('printer_selection.select_trays'), toggleFlow: "horizontal", optionFlow: "horizontal", options: this.selectedPrinterConfig.Trays &&
                this.selectedPrinterConfig.Trays.length >= 1 &&
                this.selectedPrinterConfig.Trays.map((trays) => ({
                    title: trays.Name,
                    id: trays.Index,
                    meta: '',
                    type: 'tray',
                })), preSelected: this.selectedPrinter.id &&
                ((_o = this.selectedPrinterConfig.Trays) === null || _o === void 0 ? void 0 : _o.find((el) => el.Name.includes(this.selectedPrinterConfig.Default.Tray)))
                ? this.selectedPrinterConfig.Default.Tray
                : null })) : null, h("ezp-input", { icon: "paper_range", suffix: "", placeholder: "1-2,4-5,8", value: this.selectedProperties.PageRanges, eventType: "paper_ranges", type: "text", label: i18next.t('printer_selection.page_ranges') })), h("ezp-stepper", { label: i18next.t('printer_selection.copies'), icon: "copies" })), h("div", { id: "footer" }, h("ezp-text-button", { type: "button", level: "secondary", onClick: this.handleCancel, label: i18next.t('button_actions.cancel'), class: "action", id: "cancel" }), h("ezp-text-button", { disabled: this.selectedPrinter.id === '' || this.printProcessing || this.pageRangeInvalid, type: "button", onClick: this.handlePrint, label: i18next.t('button_actions.print'), ref: (button) => (this.printButton = button), class: "action", id: "print" })), !this.hidemenu && h("ezp-user-menu", { open: this.userMenuOpen, name: this.userName }))));
    }
    static get is() { return "ezp-printer-selection"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["ezp-printer-selection.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ezp-printer-selection.css"]
        };
    }
    static get properties() {
        return {
            "clientID": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\nProperties"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "client-i-d"
            },
            "redirectURI": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "redirect-u-r-i"
            },
            "filename": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "filename"
            },
            "fileurl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "fileurl"
            },
            "filetype": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "filetype"
            },
            "fileid": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "fileid"
            },
            "files": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "File[]",
                    "resolved": "File[]",
                    "references": {
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "hidemenu": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "hidemenu",
                "defaultValue": "false"
            },
            "hideheader": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "hideheader",
                "defaultValue": "false"
            },
            "seamless": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "seamless"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "printProcessing": {},
            "pageRangeInvalid": {},
            "uploading": {},
            "preparingUpload": {},
            "printSuccess": {},
            "printFailed": {},
            "notSupported": {},
            "noPrinters": {},
            "hubDriverError": {},
            "userMenuOpen": {},
            "printStopped": {},
            "userName": {},
            "printers": {},
            "selectedPrinter": {},
            "printerConfig": {},
            "selectedPrinterConfig": {},
            "selectedProperties": {},
            "paperid": {},
            "currentFileIndex": {},
            "totalFiles": {},
            "failedFiles": {},
            "successfulFiles": {},
            "partialSuccess": {}
        };
    }
    static get events() {
        return [{
                "method": "printCancel",
                "name": "printCancel",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Description..."
                },
                "complexType": {
                    "original": "MouseEvent",
                    "resolved": "MouseEvent",
                    "references": {
                        "MouseEvent": {
                            "location": "global",
                            "id": "global::MouseEvent"
                        }
                    }
                }
            }, {
                "method": "printSubmit",
                "name": "printSubmit",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Description..."
                },
                "complexType": {
                    "original": "MouseEvent",
                    "resolved": "MouseEvent",
                    "references": {
                        "MouseEvent": {
                            "location": "global",
                            "id": "global::MouseEvent"
                        }
                    }
                }
            }, {
                "method": "logout",
                "name": "logout",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "MouseEvent",
                    "resolved": "MouseEvent",
                    "references": {
                        "MouseEvent": {
                            "location": "global",
                            "id": "global::MouseEvent"
                        }
                    }
                }
            }];
    }
    static get listeners() {
        return [{
                "name": "inputValueChanged",
                "method": "listenInputValueChanged",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "selectSelection",
                "method": "listenSelectSelection",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "stepperChanged",
                "method": "listenStepperChanged",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "userMenuClosure",
                "method": "listenUserMenuClosure",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "logoutEmitter",
                "method": "listenLogout",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "statusCancel",
                "method": "listenStatusCancel",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "statusClose",
                "method": "listenStatusClose",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "statusRetry",
                "method": "listenStatusRetry",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
