(function (paw, utils, inventoryFixedAssetsService) {
    function InventoryFixedAssetsCreate(model, settings, localization) {
        this.model = paw.lang.append({
            acKey: undefined,
            qid: undefined,
            status: undefined,
            type: undefined
        }, model);
        
        this.settings = paw.lang.append({
            $form: undefined,
            $saveBtn: undefined,
            $deleteBtn: undefined,
            $confirmBtn: undefined,
            $createBtn: undefined,
            $wizardButton: undefined,
            $typeInput: undefined,
            $statusInput: undefined,
            editUrl: undefined,
            editMode: false,
            ident: {},
            formatting: {
                decimalPlacesPrice: 2,
                decimalPlacesQuantity: 1
            }
        }, settings);
        this.localization = paw.lang.append({
            language: "@Loc.Language",
            deleteInventoryFixedAssetsMsg: "@Loc.DeleteInventoryDocument",
            noResults: '@Loc.NoResults',
            name: '@Loc.Name',
            ident: '@Loc.Ident',
            price: '@Loc.Price',
            stock: '@Loc.Stock',
            confirmDeleteMsg: '@Loc.ConfirmDeleteItemMessage',
            no: '@Loc.No',
            yes: '@Loc.Yes',
            dateFormat: '@DateFormat',
            confirmFill: '@Loc.InventoryFixedAssetConfirmFill',
            moveErrorNothingRegistered: '@Loc.InventoryFixedAssetsMoveNothingRegistered',
            confirmActivationDatesFill: '@Loc.InventoryFixedAssetsEmptyDates',
            moveErrorMissingFields: '@Loc.InventoryFixedAssetsMoveMissingFields',
            deprecGrp: '@Loc.DeprecGrp',
            classif: '@Loc.Classification',
            setOf: '@Loc.SetOf',
            ok: '@Loc.OK',
            documentAlreadyConfirmed: '@Loc.DocumentAlreadyConfirmedCantChange',
            confirmExport: '@Loc.InventoryFixedAssetsExportConfirmation',
            exportLiquidatedFixedAssets: '@Loc.InventoryFixedAssetsExportLiquidatedFA',
            ifaNotEmpty: '@Loc.InventoryFixedAssetsBasicImportIFANotEmpty',
            importConfirmation: '@Loc.InventoryFixedAssetsImportConfirmation',
            importFileStructureError: '@Loc.InventoryFixedAssetsImportFileStructureError',
            operationCompleted: '@Loc.OperationCompleted'
        }, localization);

        this.idents = new paw.view.inventoryFixedAssets.InventoryFixedAssetsIdents(this, this.settings.ident, this.localization, this.settings.formatting, this.settings.editMode);
    }

    InventoryFixedAssetsCreate.prototype.init = function () {
        var self = this;
        this.idents.init();
        this.bootstrapComponents();

        this.settings.$statusInput.change(function () {
            if (self.model.status === 'P') {
                if ($(this).val() !== self.model.status) {
                    self.settings.$saveBtn.attr('disabled', false);
                    self.settings.$saveBtn.removeClass('disabled');
                }
                else {
                    self.settings.$saveBtn.attr('disabled', true);
                    self.settings.$saveBtn.addClass('disabled');
                }
            }
        });
        this.settings.$typeInput.change(function () {
            if (self.model.status === 'P') {
                return;
            }
            self.model.type = $(this).val();
        });
    };

    InventoryFixedAssetsCreate.prototype.onSave = function (e) {
        var self = this;
        var status = self.model.status;
        this.saveData().then(function () {
            if (!self.settings.editMode || self.model.status !== status) {
                location.reload();
            }
        });
        
    };

    InventoryFixedAssetsCreate.prototype.onRemove = function () {
        var data = this.compileDataModelFromFormData();
        this.showDeleteConfirmation(function () {
            return inventoryFixedAssetsService.remove({
                AcKey: data.AcKey
            });
        });
    };

    InventoryFixedAssetsCreate.prototype.onConfirm = function () {
        var self = this;
        utils.async.asyncAction(function () {
            return inventoryFixedAssetsService.confirm(self.model.qid).then(function () {
                location.reload();
            });
        }, this.settings.$confirmBtn, [
            this.settings.$deleteBtn,
            this.settings.$saveBtn,
            this.settings.$createBtn,
            this.settings.$wizardButton
        ]);
    };

    InventoryFixedAssetsCreate.prototype.onExport = function () {
        var self = this;
        utils.async.asyncAction(function () {
            return self.showMessageDialog('exportConfirmation', self.localization.confirmExport).then(function (confirmed) {
                if (confirmed) {
                    self.showMessageDialog('exportLiquidatedFA', self.localization.exportLiquidatedFixedAssets).then(function (exportLiquidatedFA) {
                        return inventoryFixedAssetsService.export({
                            Qid: self.model.qid,
                            ExportLiquidatedFA: exportLiquidatedFA
                        }); 
                    });
                }
            });
            
        }, this.settings.$wizardButton, [
            this.settings.$deleteBtn,
            this.settings.$saveBtn,
            this.settings.$createBtn,
            this.settings.$confirmBtn
        ]);
    };

    InventoryFixedAssetsCreate.prototype.onImportBasic = function () {
        this.showImportBasicDialog();
    };
    
    InventoryFixedAssetsCreate.prototype.onImportAdvanced = function () {
        return this.showImportAdvancedDialog();
    };

    InventoryFixedAssetsCreate.prototype.onFill = function () {
        var self = this;
        
        utils.async.asyncAction(function () {
            return inventoryFixedAssetsService.fetchStatus(self.model.qid).then(function (resp) {
                if (resp.Status === 'P') {
                    self.showMessageDialog('ifaConfirmed', self.localization.documentAlreadyConfirmed, 'error');
                    return;
                }

                return self.showMessageDialog("fillConfirmation", self.localization.confirmFill).then(function (confirmed) {
                    if (!confirmed) {
                        return;
                    }
                    return inventoryFixedAssetsService.fill(self.model.qid).then(function () {
                        return self.idents.fetchIdents(self.model.acKey);
                    });
                });


            });

        }, this.settings.$wizardButton, [
            this.settings.$deleteBtn,
            this.settings.$saveBtn,
            this.settings.$createBtn,
            this.settings.$confirmBtn
        ]);
    };

    InventoryFixedAssetsCreate.prototype.onFillFAFromInventory = function (deptCostDrv) {
        var self = this;
        utils.async.asyncAction(function () {
            return inventoryFixedAssetsService.fillFaFromInventory(self.model.qid, deptCostDrv);
        }, this.settings.$wizardButton, [
            this.settings.$deleteBtn,
            this.settings.$saveBtn,
            this.settings.$createBtn,
            this.settings.$confirmBtn
        ]);
    };

    InventoryFixedAssetsCreate.prototype.onDeleteIFAFromFill = function () {
        var self = this;
        this.showDeleteConfirmation(function () {
            return inventoryFixedAssetsService.deleteInventory(self.model.qid);
        });
    };

    InventoryFixedAssetsCreate.prototype.onMoveToRegister = function () {
        var self = this;
        utils.async.asyncAction(function () {
            if (self.model.status === 'P') {
                return self.moveToRegister(false, false, true);
            }
            return self.save().then(function () {
                return self.moveToRegister(false, false, true);
            });
        }, this.settings.$wizardButton, [
            this.settings.$deleteBtn,
            this.settings.$saveBtn,
            this.settings.$createBtn,
            this.settings.$confirmBtn
        ]);
    };

    InventoryFixedAssetsCreate.prototype.saveData = function () {
        var self = this;
        return utils.async.asyncAction(function () {
            return self.save();
        }, this.settings.$saveBtn, [
            this.settings.$deleteBtn,
            this.settings.$confirmBtn,
            this.settings.$createBtn,
            this.settings.$wizardButton
        ]);
    };

    InventoryFixedAssetsCreate.prototype.save = function () {
        var self = this;
        var data = this.compileDataModelFromFormData();
        if (this.settings.editMode) {
            return inventoryFixedAssetsService.update(data).then(function (response) {
                self.model.status = response.data.Status;
                self.model.type = response.data.Type;
                return response;
            });
        }
        return inventoryFixedAssetsService.create(data).then(function (response) {
            if (!self.settings.editMode) {
                self.model.acKey = response.data.AcKey;
                self.model.status = response.data.Status;
                self.model.type = response.data.Type;
                window.history.pushState({}, null, self.settings.editUrl + response.data.AcKey);
            }
        });
    };

    InventoryFixedAssetsCreate.prototype.basicImport = function (dto) {
        var self = this;
        return inventoryFixedAssetsService.basicImport(dto).then(function (resp) {
            if (!resp.Success) {
                switch (resp.Error) {
                    case 'LOCKED':
                        return self.showMessageDialog('basicImportLocked', self.localization.documentAlreadyConfirmed, 'error');
                    case 'NOT_EMPTY':
                        return self.showMessageDialog('ifaNotEmpty', self.localization.ifaNotEmpty).then(function (confirmed) {
                            if (confirmed) {
                                dto.checkEmptyIFA = false;
                                dto.addMissingRecords = true;
                                return self.basicImport(dto);
                            }
                            return false;
                        });
                    case 'FILE_STRUCTURE':
                        return self.showMessageDialog(
                            'importFileStructure',
                            self.localization.importFileStructureError
                                .replace('%f', resp.FileError.Filename)
                                .replace('%d', resp.FileError.Line)
                                .replace('%s', resp.FileError.Row),
                            'error');
                    case 'IMPORT_FAILED':
                        return self.showMessageDialog(
                            'importFailed',
                            resp.ErrorDetails,
                            'error');
                }
            }
            return self.showMessageDialog('operationCompleted', self.localization.operationCompleted, 'info').then(function () {
                return true;
            });
        });
    };

    InventoryFixedAssetsCreate.prototype.advancedImport = function (dto) {
        var self = this;
        return inventoryFixedAssetsService.advancedImport(dto).then(function (resp) {
            if (!resp.Success) {
                switch (resp.Error) {
                    case 'LOCKED':
                        return self.showMessageDialog('advancedImportLocked', self.localization.documentAlreadyConfirmed, 'error');
                    case 'NOT_EMPTY':
                        return self.showMessageDialog('ifaNotEmpty', self.localization.ifaNotEmpty).then(function (confirmed) {
                            if (confirmed) {
                                dto.checkEmptyIFA = false;
                                dto.addMissingRecords = true;
                                return self.advancedImport(dto);
                            }
                        });
                }
            }
            return self.showMessageDialog('operationCompleted', self.localization.operationCompleted, 'info').then(function () {
                return true;
            });
        });
    };

    InventoryFixedAssetsCreate.prototype.compileDataModelFromFormData = function () {
        var formData = this.settings.$form.serializeArray();
        if (this.model.status !== 'P') {
            formData.push({ name: 'ItemsJsonString', value: JSON.stringify(this.idents.idents) });
        }
        var data = {};
        utils.iterable.iterate(formData, function (item) {
            data[item.name] = item.value;
        });
        return data;
    };

    InventoryFixedAssetsCreate.prototype.moveToRegister = function (checkActivationDates, fillActivationDates, checkMissingFields) {
        var self = this;
        return inventoryFixedAssetsService.moveToRegister({
            Qid: self.model.qid,
            CheckActivationDates: checkActivationDates,
            FillActivationDates: fillActivationDates,
            CheckMissingFields: checkMissingFields,
            Type: self.model.type
        }).then(function (resp) {
            if (!resp.Success) {
                switch (resp.Error) {
                    case 'NOTHING_REGISTERED':
                        return self.showMessageDialog(resp.Error, self.localization.moveErrorNothingRegistered, "error");
                    case 'EMPTY_DATES':
                        return self.showMessageDialog(resp.Error, self.localization.confirmActivationDatesFill).then(function (fillActivationDates) {
                            return self.moveToRegister(false, fillActivationDates, true);
                        });
                    case 'MISSING_FIELDS': {
                        var fields = [];
                        utils.iterable.iterate(resp.Errors, function (inventNum, errorId) {
                            switch (errorId) {
                                case 'DEPREC_GRP':
                                    fields.push(self.localization.deprecGrp);
                                    break;
                                case 'CLASSIF':
                                    fields.push(self.localization.classif);
                                    break;
                                case 'SET_OF':
                                    fields.push(self.localization.setOf);
                                    break;
                            }
                        });
                        return self.showMessageDialog(resp.Error, self.localization.moveErrorMissingFields.replace('%s', fields.join(', '))).then(function (confirmed) {
                            if (confirmed) {
                                return self.moveToRegister(false, fillActivationDates, false);
                            }
                        });
                    }
                }
            }
        });
    };

    InventoryFixedAssetsCreate.prototype.bootstrapComponents = function () {
        $(".datepicker").datepicker({
            format: this.localization.dateFormat,
            language: this.localization.language
        }).on('changeDate', function () {
            $(this).datepicker('hide');
        });
    };

    InventoryFixedAssetsCreate.prototype.showMessageDialog = function (dialogId, message, type) {
        var d = utils.async.defer();
        var type = utils.value.notSet(type) ? "question" : type;
        var actions = [
            {
                icon: 'fa fa-check',
                text: this.localization.ok,
                action: async function () {
                    d.resolve(true);
                },
                closeOnAction: true,
                type: 'primary'
            }];

        if (type === "question") {
            actions = [
                {
                    icon: 'fa fa-times',
                    text: this.localization.no,
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: this.localization.yes,
                    action: async function () {
                        d.resolve(true);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ];
        }

        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            id: dialogId + "Modal",
            type: type,
            text: message,
            onClose: function () {
                d.resolve(false);
            },
            buttons: actions
        });
        return d.promise;
    };

    InventoryFixedAssetsCreate.prototype.showImportBasicDialog = function () {
        var self = this;
        var $modal = $('#importBasicModal');

        var dri = [];
        var $fileInputs = $modal.find('input[type=file].dropify');
        $fileInputs.each(function () {
            dri.push($(this).dropify());
        });

        var $importAction = $('#importBasic');
        $modal.modal('show');
        $modal.on('hidden.bs.modal', function () {
            utils.iterable.iterate(dri, function (dr) {
                dr.data('dropify').clearElement();
            });
            dri = [];

            $importAction.off('click');
        });

        $importAction.on('click', function () {
            var newLocationsFile = $('#importBasicFileNewLocations')[0].files[0];
            var newAssetsFile = $('#importBasicFileNewAssets')[0].files[0];
            var assetsFile = $('#importBasicFileAssets')[0].files[0];

            if (utils.value.notSet(newLocationsFile) && utils.value.notSet(newAssetsFile) && utils.value.notSet(assetsFile)) {
                // error?
                return;
            }

            utils.async.asyncAction(function () {
                return self.showMessageDialog('confirmImport', self.localization.importConfirmation).then(function (confirmed) {
                    if (confirmed) {
                        return utils.async.asyncAction(function () {
                            return self.basicImport({
                                qid: self.model.qid,
                                checkEmptyIFA: true,
                                newLocations: newLocationsFile,
                                newAssets: newAssetsFile,
                                assets: assetsFile
                            });
                        }, $importAction).then(function (completed) {
                            if (completed === true) {
                                self.idents.fetchIdents(self.model.acKey);
                                $modal.modal('hide');
                            }
                        });
                    }
                });
            }, self.settings.$wizardButton, [
                self.settings.$deleteBtn,
                self.settings.$saveBtn,
                self.settings.$createBtn,
                self.settings.$confirmBtn
            ]);
            
            
        });
    };

    InventoryFixedAssetsCreate.prototype.showImportAdvancedDialog = function () {
        var self = this;
        var $modal = $('#importAdvancedModal');

        var dri = [];
        var $fileInputs = $modal.find('input[type=file].dropify');
        $fileInputs.each(function () {
            dri.push($(this).dropify());
        });

        var $importAction = $('#importAdvanced');
        $modal.modal('show');
        $modal.on('hidden.bs.modal', function () {
            utils.iterable.iterate(dri, function (dr) {
                dr.data('dropify').clearElement();
            });
            dri = [];

            $importAction.off('click');
        });

        $importAction.on('click', function () {
            var newLocationsFile = $('#importAdvancedFileNewLocations')[0].files[0];
            var newAssetsFile = $('#importAdvancedFileNewAssets')[0].files[0];

            if (utils.value.notSet(newLocationsFile) && utils.value.notSet(newAssetsFile)) {
                // error?
                return;
            }

            utils.async.asyncAction(function () {
                return self.showMessageDialog('confirmImport', self.localization.importConfirmation).then(function (confirmed) {
                    if (confirmed) {
                        return utils.async.asyncAction(function () {
                            return self.advancedImport({
                                qid: self.model.qid,
                                checkEmptyIFA: true,
                                newLocations: newLocationsFile,
                                newAssets: newAssetsFile
                            });
                        }, $importAction).then(function (completed) {
                            if (completed === true) {
                                self.idents.fetchIdents(self.model.acKey);
                                $modal.modal('hide');
                            }
                        });
                    }
                });
            }, self.settings.$wizardButton, [
                self.settings.$deleteBtn,
                self.settings.$saveBtn,
                self.settings.$createBtn,
                self.settings.$confirmBtn
            ]);

            
        });

        return utils.async.promise();
    };

    InventoryFixedAssetsCreate.prototype.showDeleteConfirmation = function (onDelete) {
        var self = this;
        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            id: "deleteInventoryFixedAssetsAlertModal",
            type: "question",
            text: self.localization.deleteInventoryFixedAssetsMsg,
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: self.localization.no,
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: self.localization.yes,
                    action: async function () {
                        utils.async.asyncAction(function () {
                            return onDelete();
                        }, self.settings.$deleteBtn, [
                            self.settings.$saveBtn,
                            self.settings.$confirmBtn,
                            self.settings.$createBtn,
                            self.settings.$wizardButton
                        ]).then(function () {
                            location.href = self.settings.indexUrl;
                        });

                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    };

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