(function (paw, utils) {
    function InventoryFixedAssetsService() {
        this.settings = {
            createApiUrl: undefined,
            updateApiUrl: undefined,
            removeApiUrl: undefined,
            confirmApiUrl: undefined,
            deleteInventoryApiUrl: undefined,
            exportApiUrl: undefined,
            fillApiUrl: undefined,
            statusApiUrl: undefined,
            moveToRegisterApiUrl: undefined,
            checkEmptyActivationDatesApiUrl: undefined,
            basicImportApiUrl: undefined,
            advancedImportApiUrl: undefined
        };
    }

    InventoryFixedAssetsService.prototype.setup = function (settings) {
        paw.lang.append(settings, this.settings);
    };

    InventoryFixedAssetsService.prototype.create = function (data) {
        return utils.async.post(this.settings.createApiUrl, data);
    };

    InventoryFixedAssetsService.prototype.update = function (data) {
        return utils.async.post(this.settings.updateApiUrl, data);
    };

    InventoryFixedAssetsService.prototype.remove = function (data) {
        return utils.async.post(this.settings.removeApiUrl, data);
    };

    InventoryFixedAssetsService.prototype.confirm = function (qid) {
        return utils.async.post(this.settings.confirmApiUrl + qparams({
            qid: qid
        }), null);
    };

    InventoryFixedAssetsService.prototype.fetchStatus = function (qid) {
        return utils.async.get(this.settings.statusApiUrl + qparams({
            qid: qid
        }));
    };

    InventoryFixedAssetsService.prototype.export = function (dto) {
        //return utils.async.post(this.settings.exportApiUrl, dto);

        var d = utils.async.defer();
        $.ajax({
            type: 'POST',
            url: this.settings.exportApiUrl,
            data: dto,
            success: function (data, textStatus, jqXHR) {
                const contentType = jqXHR.getResponseHeader('Content-Type');
                if (contentType && contentType.includes('multipart/mixed')) {
                    const boundary = data.split('\n')[0].trim();
                    const parts = jqXHR.responseText.split(new RegExp(`${boundary}(--)?`, 'g')).filter(part => part && part.trim() !== '' && part.trim() !== '--');
                    var files = parts.map(part => {
                        // Split each part into headers and body
                        const headerBodySplit = part.split("\r\n\r\n");
                        const headers = headerBodySplit[0];
                        const body = headerBodySplit.slice(1).join("\r\n\r\n").trim(); // Join remaining parts as body and trim

                        // Extract filename from Content-Disposition header
                        const contentDisposition = headers.match(/Content-Disposition: attachment; filename="?(.+?)"?$/);
                        const filename = contentDisposition ? contentDisposition[1] : "unknown.txt";

                        return {
                            filename: filename,
                            content: body
                        };
                    });
                    files.forEach(file => {
                        const blob = new Blob([file.content], { type: 'text/plain' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = file.filename;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                    });
                }
                d.resolve();
            },
            error: function () {
                d.reject();
            }
        });
        return d.promise;
    };

    InventoryFixedAssetsService.prototype.basicImport = function (dto) {
        var formData = new FormData();
        formData.append('Qid', dto.qid);
        formData.append('CheckEmptyIFA', dto.checkEmptyIFA);
        formData.append('AddMissingRecords', dto.addMissingRecords);
        formData.append('NewLocations', dto.newLocations);
        formData.append('NewAssets', dto.newAssets);
        formData.append('Assets', dto.assets);
        
        console.log("Form data", formData, dto);
        var d = utils.async.defer();
        $.ajax({
            url: this.settings.basicImportApiUrl,
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                console.log("Response", response);
                d.resolve(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error('An error occurred while uploading the files.');
                d.reject();
            }
        });
        return d.promise;
    };

    InventoryFixedAssetsService.prototype.advancedImport = function (dto) {
        var formData = new FormData();
        formData.append('Qid', dto.qid);
        formData.append('CheckEmptyIFA', dto.checkEmptyIFA);
        formData.append('AddMissingRecords', dto.addMissingRecords);
        formData.append('NewLocations', dto.newLocations);
        formData.append('NewAssets', dto.newAssets);

        console.log("Form data", formData, dto);
        var d = utils.async.defer();
        $.ajax({
            url: this.settings.advancedImportApiUrl,
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                console.log("Response", response);
                d.resolve(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error('An error occurred while uploading the files.');
                d.reject();
            }
        });
        return d.promise;
    };

    InventoryFixedAssetsService.prototype.fill = function (qid) {
        return utils.async.post(this.settings.fillApiUrl + qparams({
            qid: qid
        }));
    };

    InventoryFixedAssetsService.prototype.checkEmptyActivationDates = function (qid) {
        return utils.async.get(this.settings.checkEmptyActivationDatesApiUrl + qparams({
            qid: qid
        }));
    };

    InventoryFixedAssetsService.prototype.moveToRegister = function (dto) {
        return utils.async.post(this.settings.moveToRegisterApiUrl, dto);
    };

    InventoryFixedAssetsService.prototype.fillFaFromInventory = function (qid, deptCostDrv) {
        return utils.async.post(this.settings.fillFaFromInventoryApiUrl + qparams({
            qid: qid,
            deptCostDrv: deptCostDrv
        }));
    };

    InventoryFixedAssetsService.prototype.deleteInventory = function (qid) {
        return utils.async.post(this.settings.deleteInventoryApiUrl + qparams({
            qid: qid
        }));
    }; 

    paw.view.inventoryFixedAssets.inventoryFixedAssetsService = new InventoryFixedAssetsService();
})(paw, paw.utils);