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 { DocumentStoreService } from '../../../services/document-store/document-store.service';
import { Constants } from '../../../commons/constants';
import { flatMap } from 'rxjs/operators';
import { CaseFieldService } from '../../../services';
var WriteDocumentFieldComponent = /** @class */ (function (_super) {
    __extends(WriteDocumentFieldComponent, _super);
    function WriteDocumentFieldComponent(documentStore, caseFieldService) {
        var _this = _super.call(this) || this;
        _this.documentStore = documentStore;
        _this.caseFieldService = caseFieldService;
        _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.ngOnInit = function () {
        var document = this.caseField.value;
        if (document) {
            this.createDocumentGroup(document.id, document.name);
        }
    };
    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 === 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('id').valid &&
            !this.uploadedDocument.get('name').valid;
        return validation;
    };
    WriteDocumentFieldComponent.prototype.fileChangeEvent = function (fileInput) {
        // TODO caching of pre-signed URLs
        // Is there a pre-signed upload URL?
        // Is the pre-signed upload URL still valid?
        // If no -> generate new pre-signed URL
        var _this = this;
        if (fileInput.target.files[0]) {
            var file_1 = fileInput.target.files[0];
            var metadata_1 = this.getDocumentMetadata(file_1);
            this.documentStore.newUploadUrl(metadata_1)
                .pipe(flatMap(function (document) { return _this.documentStore.upload(file_1, document, metadata_1); }))
                .subscribe(function (documentId) {
                _this.setDocumentGroup(documentId, file_1.name);
                _this.valid = true;
            }, function (error) {
                _this.uploadError = _this.getErrorMessage(error);
                _this.valid = false;
            });
        }
        else {
            this.clearDocumentGroup();
            if (this.isAMandatoryComponent()) {
                this.displayFileErrors();
            }
        }
    };
    WriteDocumentFieldComponent.prototype.createDocumentGroup = function (id, name) {
        var validator = this.caseFieldService.isMandatory(this.caseField) ? Validators.required : undefined;
        this.uploadedDocument = this.registerControl(new FormGroup({
            id: new FormControl(id || '', validator),
            name: new FormControl(name || '', validator),
        }));
    };
    WriteDocumentFieldComponent.prototype.setDocumentGroup = function (id, name) {
        if (!this.uploadedDocument) {
            this.createDocumentGroup(id, name);
        }
        else {
            this.uploadedDocument.get('id').setValue(id);
            this.uploadedDocument.get('name').setValue(name);
        }
    };
    WriteDocumentFieldComponent.prototype.clearDocumentGroup = function () {
        this.setDocumentGroup(null, null);
    };
    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.getUploadedFileName = function () {
        if (this.uploadedDocument) {
            return this.uploadedDocument.get('document_filename').value;
        }
        else {
            return undefined;
        }
    };
    WriteDocumentFieldComponent.prototype.getDocumentMetadata = function (file) {
        return {
            case: this.caseId,
            field: this.fieldMetadata(),
            filename: file.name,
        };
    };
    WriteDocumentFieldComponent.prototype.fieldMetadata = function () {
        // FIXME add post-processing to convert ID into usable field path for collection and complex fields
        // eg. defaultProductSyndicateStructure_0_defaultSyndicateStructure_0_startTime ->
        // defaultProductSyndicateStructure[].defaultSyndicateStructure[].startTime
        var fieldId = this.id();
        return fieldId;
    };
    __decorate([
        ViewChild('fileInput', { static: true }),
        __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      <input class=\"form-control bottom-30\"\n             [id]=\"id()\"\n             type=\"file\"\n             (keydown.Tab)=\"fileValidationsOnTab()\"\n             (change)=\"fileChangeEvent($event)\"\n             accept=\"{{caseField.field_type.regular_expression}}\"\n             #fileInput/>\n    </div>\n  "
        }),
        __metadata("design:paramtypes", [DocumentStoreService,
            CaseFieldService])
    ], WriteDocumentFieldComponent);
    return WriteDocumentFieldComponent;
}(AbstractFieldWriteComponent));
export { WriteDocumentFieldComponent };
//# sourceMappingURL=write-document-field.component.js.map