var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, ViewChild, ElementRef, HostListener } from '@angular/core';
import { AbstractFieldWriteComponent } from '../base-field/abstract-field-write.component';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { DocumentManagementService } from '../../../services/document-management/document-management.service';
import { MatDialog, MatDialogConfig } from '@angular/material';
import { DocumentDialogComponent } from '../../dialogs/document-dialog/document-dialog.component';
import { Constants } from '../../../commons/constants';
var WriteDocumentFieldComponent = /** @class */ (function (_super) {
    __extends(WriteDocumentFieldComponent, _super);
    function WriteDocumentFieldComponent(documentManagement, dialog) {
        var _this = _super.call(this) || this;
        _this.documentManagement = documentManagement;
        _this.dialog = dialog;
        _this.valid = true;
        return _this;
    }
    WriteDocumentFieldComponent.prototype.clickout = function (event) {
        // Capturing the event of of the associated  ElementRef <input type="file" #fileInpu
        if (this.fileInput.nativeElement.contains(event.target)) {
            this.clickInsideTheDocument = true;
        }
        else {
            this.fileValidations();
        }
    };
    WriteDocumentFieldComponent.prototype.initDialog = function () {
        this.dialogConfig = new MatDialogConfig();
        this.dialogConfig.disableClose = true;
        this.dialogConfig.autoFocus = true;
        this.dialogConfig.ariaLabel = 'Label';
        this.dialogConfig.height = '245px';
        this.dialogConfig.width = '550px';
        this.dialogConfig.panelClass = 'dialog';
        this.dialogConfig.closeOnNavigation = false;
        this.dialogConfig.position = {
            top: window.innerHeight / 2 - 120 + 'px', left: window.innerWidth / 2 - 275 + 'px'
        };
    };
    WriteDocumentFieldComponent.prototype.ngOnInit = function () {
        this.initDialog();
        var document = this.caseField.value;
        if (document) {
            this.createDocumentGroup(document.document_url, document.document_binary_url, document.document_filename);
        }
    };
    WriteDocumentFieldComponent.prototype.fileValidations = function () {
        if (this.isAMandatoryComponent()) {
            if (this.clickInsideTheDocument && this.validateFormUploadedDocument()) {
                this.displayFileErrors();
            }
        }
    };
    WriteDocumentFieldComponent.prototype.fileValidationsOnTab = function () {
        if (this.isAMandatoryComponent()) {
            if (this.validateFormUploadedDocument()) {
                this.displayFileErrors();
            }
        }
    };
    WriteDocumentFieldComponent.prototype.isAMandatoryComponent = function () {
        return this.caseField.display_context && this.caseField.display_context === Constants.MANDATORY;
    };
    WriteDocumentFieldComponent.prototype.displayFileErrors = function () {
        this.valid = false;
        this.uploadError = 'File required';
    };
    WriteDocumentFieldComponent.prototype.validateFormUploadedDocument = function () {
        if (!this.uploadedDocument) {
            return true;
        }
        var validation = !this.uploadedDocument.get('document_url').valid &&
            !this.uploadedDocument.get('document_binary_url').valid &&
            !this.uploadedDocument.get('document_filename').valid;
        return validation;
    };
    WriteDocumentFieldComponent.prototype.fileChangeEvent = function (fileInput) {
        var _this = this;
        if (fileInput.target.files[0]) {
            this.selectedFile = fileInput.target.files[0];
            // Perform the file upload immediately on file selection
            var documentUpload = new FormData();
            documentUpload.append('files', this.selectedFile, this.selectedFile.name);
            documentUpload.append('classification', 'PUBLIC');
            this.documentManagement.uploadFile(documentUpload).subscribe(function (result) {
                if (!_this.uploadedDocument) {
                    _this.createDocumentGroup();
                }
                var document = result._embedded.documents[0];
                _this.setDocumentGroupValues(document._links.self.href, document._links.binary.href, document.originalDocumentName);
                _this.valid = true;
            }, function (error) {
                _this.uploadError = _this.getErrorMessage(error);
                _this.valid = false;
            });
        }
        else {
            this.selectedFile = null;
            this.uploadedDocument.get('document_url').setValue(null);
            this.uploadedDocument.get('document_binary_url').setValue(null);
            this.uploadedDocument.get('document_filename').setValue(null);
            if (this.isAMandatoryComponent()) {
                this.displayFileErrors();
            }
        }
    };
    WriteDocumentFieldComponent.prototype.createDocumentGroup = function (url, binaryUrl, filename) {
        this.uploadedDocument = this.registerControl(new FormGroup({
            document_url: new FormControl(url || '', Validators.required),
            document_binary_url: new FormControl(binaryUrl || '', Validators.required),
            document_filename: new FormControl(filename || '', Validators.required)
        }));
    };
    WriteDocumentFieldComponent.prototype.setDocumentGroupValues = function (url, binaryUrl, filename) {
        this.uploadedDocument.get('document_url').setValue(url);
        this.uploadedDocument.get('document_binary_url').setValue(binaryUrl);
        this.uploadedDocument.get('document_filename').setValue(filename);
    };
    WriteDocumentFieldComponent.prototype.getErrorMessage = function (error) {
        // Document Management unavailable
        if (0 === error.status || 502 === error.status) {
            return 'Document upload facility is not available at the moment';
        }
        return error.error;
    };
    WriteDocumentFieldComponent.prototype.openFileDialog = function () {
        this.fileInput.nativeElement.click();
    };
    WriteDocumentFieldComponent.prototype.fileSelectEvent = function () {
        if (this.caseField.value) {
            this.openDialog(this.dialogConfig);
        }
        else {
            this.openFileDialog();
        }
    };
    WriteDocumentFieldComponent.prototype.openDialog = function (dialogConfig) {
        var _this = this;
        var dialogRef = this.dialog.open(DocumentDialogComponent, dialogConfig);
        dialogRef.beforeClose().subscribe(function (result) {
            _this.confirmReplaceResult = result;
            _this.triggerReplace();
        });
    };
    WriteDocumentFieldComponent.prototype.triggerReplace = function () {
        if (this.confirmReplaceResult === 'Replace') {
            this.openFileDialog();
        }
    };
    WriteDocumentFieldComponent.prototype.getUploadedFileName = function () {
        if (this.uploadedDocument) {
            return this.uploadedDocument.get('document_filename').value;
        }
        else {
            return undefined;
        }
    };
    __decorate([
        ViewChild('fileInput'),
        __metadata("design:type", ElementRef)
    ], WriteDocumentFieldComponent.prototype, "fileInput", void 0);
    __decorate([
        HostListener('document:click', ['$event']),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], WriteDocumentFieldComponent.prototype, "clickout", null);
    WriteDocumentFieldComponent = __decorate([
        Component({
            selector: 'ccd-write-document-field',
            template: "\n    <div class=\"form-group\" [ngClass]=\"{'form-group-error': !valid}\">\n      <label [for]=\"id()\">\n        <span class=\"form-label\" attr.aria-label=\"{{caseField | ccdFieldLabel}}\">{{caseField | ccdFieldLabel}}</span>\n        <span class=\"form-hint\" *ngIf=\"caseField.hint_text\">{{caseField.hint_text}}</span>\n        <span class=\"error-message\" *ngIf=\"uploadError && !valid\">{{uploadError}}</span>\n      </label>\n\n      <div>\n        <!--<span *ngIf=\"getUploadedFileName()\" class=\"text-16\">File name: {{getUploadedFileName()}}</span>-->\n        <ccd-read-document-field *ngIf=\"caseField\" [caseField]=\"caseField\"></ccd-read-document-field>\n      </div>\n\n      <div style='position:relative'>\n\n        <div id='fileInputWrapper' (click)=\"fileSelectEvent()\"  ></div>\n        <input class=\"form-control bottom-30\" [id]=\"id()\" type=\"file\" (keydown.Tab)=\"fileValidationsOnTab()\" (change)=\"fileChangeEvent($event)\"\n               accept=\"{{caseField.field_type.regular_expression}}\" #fileInput/>\n      </div>\n    </div>\n  "
        }),
        __metadata("design:paramtypes", [DocumentManagementService, MatDialog])
    ], WriteDocumentFieldComponent);
    return WriteDocumentFieldComponent;
}(AbstractFieldWriteComponent));
export { WriteDocumentFieldComponent };
//# sourceMappingURL=write-document-field.component.js.map