/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
 */
import * as tslib_1 from "tslib";
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';
import { FVAbstractControl } from '../../../shared/abstract-control.component';
import { ProcessService } from '../../../../services/process.service';
import { ApiService, DGSNotificationService } from '@dotgov/core';
var FVControlsUploadFileComponent = /** @class */ (function (_super) {
    tslib_1.__extends(FVControlsUploadFileComponent, _super);
    function FVControlsUploadFileComponent(process, api, notification) {
        var _this = _super.call(this, process) || this;
        _this.process = process;
        _this.api = api;
        _this.notification = notification;
        _this._files = [];
        return _this;
    }
    /**
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.ngAfterViewInit = /**
     * @return {?}
     */
    function () {
        _super.prototype.setValue.call(this, this.files);
        _super.prototype.saveKey.call(this);
        _super.prototype.evalEventJs.call(this);
        this.fetchCurrent();
    };
    /**
     * @param {?} event
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.dragover = /**
     * @param {?} event
     * @return {?}
     */
    function (event) {
        event.stopPropagation();
        event.preventDefault();
        // Explicitly show this is a copy.
        event.dataTransfer.dropEffect = 'copy';
    };
    /**
     * @param {?} event
     * @param {?} files
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.addFile = /**
     * @param {?} event
     * @param {?} files
     * @return {?}
     */
    function (event, files) {
        var _this = this;
        event.stopPropagation();
        event.preventDefault();
        /** @type {?} */
        var file = files[0];
        if (!file) {
            return;
        }
        event.target.value = null;
        if (this.fileExists(file)) {
            this.notification.warning('You cant upload twice same file.');
            return;
        }
        if (!this.fileValid(file.name)) {
            this.notification.warning('You can upload only PDF, PNG, JPG, XLS, RAR, ZIP, TIFF, DOCX.');
            return;
        }
        /** @type {?} */
        var formData = new FormData();
        /** @type {?} */
        var onError = function (err) {
            _this.files = [];
            _this.notification.error(err);
            return;
        };
        /** @type {?} */
        var size = this.bytesToSize(file.size);
        if (!size) {
            return onError('Something went wrong.');
        }
        /** @type {?} */
        var isValidSize = size.sizeIndex <= 2 && !(size.sizeIndex === 2 && Number(size.finalSize) > 10);
        if (!isValidSize) {
            return onError('File must not exceed 10MB.');
        }
        formData.append('file', file, file.name);
        this.api.post('file', [], {}, formData, {
            skipCache: true,
            headers: {
                'Accept': '*/*',
            },
        }).then(function (result) {
            if (result.error) {
                return onError((result.error.error || {}).message || result.error.message || 'Something went wrong.');
            }
            result.data.size = size.finalSize + " " + size.sizeName;
            _this.files = [result.data];
        });
    };
    /**
     * @param {?} hiddenId
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.deleteFile = /**
     * @param {?} hiddenId
     * @return {?}
     */
    function (hiddenId) {
        /** @type {?} */
        var newFiles = this.files.filter(function (file) { return file.hiddenId !== hiddenId; });
        this.files = newFiles;
    };
    /**
     * @param {?} event
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.dropZoneClicked = /**
     * @param {?} event
     * @return {?}
     */
    function (event) {
        this.fileInput.element.nativeElement.click();
    };
    /**
     * @param {?} file
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.fileUrl = /**
     * @param {?} file
     * @return {?}
     */
    function (file) {
        return this.api.API + file.url;
    };
    /**
     * @param {?} bytes
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.sanitizedSize = /**
     * @param {?} bytes
     * @return {?}
     */
    function (bytes) {
        if (isNaN(bytes)) {
            return bytes;
        }
        /** @type {?} */
        var final = this.bytesToSize(bytes);
        return final.finalSize + " " + final.sizeName;
    };
    Object.defineProperty(FVControlsUploadFileComponent.prototype, "files", {
        get: /**
         * @return {?}
         */
        function () {
            return this._files;
        },
        set: /**
         * @param {?} files
         * @return {?}
         */
        function (files) {
            this._files = files;
            this.process.set(this._control.key + "-value", files);
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.fetchCurrent = /**
     * @return {?}
     */
    function () {
        /** @type {?} */
        var arrOf = function (item) {
            if (!Array.isArray(item)) {
                return item && item['fileName'] ? [item] : [];
            }
            return item;
        };
        /** @type {?} */
        var files = arrOf(this.task.componentConfig.recordData[this.control.referenceName])
            || arrOf(this.process.get(this.control.key + "-value"));
        this.files = files;
    };
    /**
     * @param {?} bytes
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.bytesToSize = /**
     * @param {?} bytes
     * @return {?}
     */
    function (bytes) {
        /** @type {?} */
        var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        if (bytes === 0) {
            return;
        }
        /** @type {?} */
        var i = Number(Math.floor(Math.log(bytes) / Math.log(1024)).toFixed(2));
        /** @type {?} */
        var finalSize = '';
        if (i === 0) {
            finalSize = String(bytes);
        }
        else {
            finalSize = (bytes / Math.pow(1024, i)).toFixed(1);
        }
        return { finalSize: finalSize, sizeName: sizes[i], sizeIndex: i, bytes: bytes };
    };
    /**
     * Returns if given file found inside active files, matching full name and size.
     * @param {?} file
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.fileExists = /**
     * Returns if given file found inside active files, matching full name and size.
     * @param {?} file
     * @return {?}
     */
    function (file) {
        var _this = this;
        return this.files && this.files.find(function (_file) {
            return _file.fileName === file.name
                && _this.sanitizedSize(file.size) === _this.sanitizedSize(_file.size);
        });
    };
    /**
     * @param {?} filename
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.getExtension = /**
     * @param {?} filename
     * @return {?}
     */
    function (filename) {
        /** @type {?} */
        var parts = filename.split('.');
        return parts[parts.length - 1];
    };
    /**
     * @param {?} filename
     * @return {?}
     */
    FVControlsUploadFileComponent.prototype.fileValid = /**
     * @param {?} filename
     * @return {?}
     */
    function (filename) {
        /** @type {?} */
        var ext = this.getExtension(filename);
        /** @type {?} */
        var allowed = ['jpg', 'jpeg', 'pdf', 'xls', 'rar', 'zip', 'tiff', 'png', 'docx'];
        return allowed.indexOf(ext.toLowerCase()) !== -1;
    };
    FVControlsUploadFileComponent.decorators = [
        { type: Component, args: [{
                    selector: 'fv-controls-upload-file',
                    template: "<div *ngIf=\"control\" class=\"controlBox\" [attr.id]=\"'control-' + control.referenceName\">\n  <i *ngIf=\"buttonsDebug\" (click)=\"debugStatus =! debugStatus\" class=\"fa fa-stethoscope\"></i>\n  <ng-container *ngIf=\"!hideLabel\">\n    <span class=\"controlName\" [attr.id]=\"'label-' + control.referenceName\">{{ control?.label | ltranslate }}</span>\n    <span *ngIf=\"control?.isRequired\" class=\"required\">*</span>\n    <i *ngIf=\"tooltip\" class=\"fa fa-question-circle\" [tooltip]=\"tooltip | ltranslate\" container=\"body\" placement=\"top\"></i>\n  </ng-container>\n  <div *ngIf=\"debugStatus\" [innerText]=\"debugText()\"></div>\n\n  <div>{{ 'Allowed file formats' | ltranslate }}: PDF, PNG, JPG, XLS, RAR, ZIP, TIFF, DOCX</div>\n  <div>{{ 'Allowed maximal file size' | ltranslate }} - 10 MB</div>\n  <div class=\"file-container\">\n    <ul class=\"list-unstyled file-list\">\n      <li class=\"file-item\" *ngFor=\"let file of files\">\n        <a [attr.id]=\"'file-' + file.fileName\" [href]=\"fileUrl(file)\" [innerText]=\"file.fileName\"></a>\n        <span class=\"file-tools\">\n          <span [innerHtml]=\"sanitizedSize(file.size)\"></span>\n          <i class=\"fa fa-trash-o\" role=\"button\" (click)=\"deleteFile(file.hiddenId)\" [tooltip]=\"'Remove' | ltranslate\"\n            placement=\"top\"></i>\n        </span>\n      </li>\n    </ul>\n  </div>\n\n  <fv-controls-validator *ngIf=\"group?.controls[control.key]\" [FVFormControl]=\"group?.controls[control.key]\" [group]=\"group\"\n    [control]=\"control\" [task]=\"task\" [tabIndex]=\"tabIndex\"></fv-controls-validator>\n  <div [ngClass]=\"{'upload-drop-zone': true, 'drop': isDragOver, 'disabled': isReadOnly}\" (dragover)=\"dragover($event)\"\n    tabindex=\"0\" (dragenter)=\"isDragOver = true\" (dragleave)=\"isDragOver = false\" (drop)=\"addFile($event, $event.dataTransfer.files)\"\n    (click)=\"dropZoneClicked($event)\" [attr.id]=\"'filezone-' + control.referenceName\">\n    <i class=\"fa fa-cloud-upload\"></i>\n    {{ 'Choose/Drop file' | translate }}\n  </div>\n\n  <input [attr.id]=\"'input-' + control.referenceName\" #fileInput type=\"file\" (change)=\"addFile($event, $event.target.files)\"\n    class=\"form-control hidden\" [name]=\"control?.key\" ngModel [disabled]=\"disabled\" [required]=\"control?.isRequired ? true : null\">\n</div>",
                    viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],
                    styles: [".col{display:inline-flex;flex-basis:0;flex-grow:1;max-width:100%;min-width:50%}.col fv-form-tab{padding:0 5px;display:block;width:100%}.col fv-form-tab .controls-row{margin:0;padding:0}.col fv-form-tab div{max-width:100%}.columns-0,.columns-1{width:100%;min-width:100%;max-width:100%}.columns-2{width:50%;min-width:50%;max-width:50%}.columns-3{width:33.33%;max-width:33.33%;min-width:33.33%}.columns-4{width:25%;max-width:25%;min-width:25%}.controlBox .input-group{display:inline-flex;width:100%;margin-top:5px}.controlBox>.input-group>button:not(.input-group-addon),.controlBox>.input-group>input,.controlBox>.input-group>select{height:40px!important;width:100%;padding:10px}.controlBox .input-group button.input-group-addon{position:relative;width:35px;height:40px}.controlBox .input-group span.controlName{color:red}.controlBox .input-group button.input-group-addon i{position:absolute;top:10px;bottom:0;left:0;right:0}.has-text-centered,.table,.table thead th{text-align:center}.gridForm{width:100%;padding:0;margin:0 0 10px}.gridForm .input-group>.form-control{max-width:50%;border-radius:unset;margin-right:10px;min-width:80px;min-height:45px}.gridForm .input-group>.addon{background:0 0;border:none;color:#36c}.grid-table tbody>tr>td{vertical-align:middle}.modal-dialog>.modal-content{max-height:100vh}.modal-content>.modal-body{max-height:85vh;overflow-y:auto}.modal-content fv-navigator{width:100%;display:block;position:relative;height:50px}.modal-content fv-navigator .docked-buttons{width:auto}.modal-content fv-navigator .btn-col:not(.bottom){max-width:unset;padding:6px!important}span.required{color:red}form:not(.ng-untouched) .ng-invalid{border:1px solid red},form:not(.ng-untouched) .ng-invalid.input-group-addon{border-left:none!important}span.error-block{color:red}@media screen and (max-width:426px){.columns-2,.columns-3,.columns-4{width:100%;max-width:100%;min-width:100%}}.tree:last-of-type(.accordion){margin:0}select:disabled{background:#eee}navigator-bot,navigator-top{display:flex}fv-menu-folder:last-of-type>accordion:last-of-type{margin:0;padding:0}.button-group>button:not(:last-child):not(:first-child){margin-left:0!important;padding-left:0!important;margin-right:0!important;padding-right:0!important}.fv_container,.fv_container>*,navigator-after,navigator-before{all:inherit!important;padding:0!important}.lookup-form .gridInputs{width:100%}.lookup-form .gridInputs select{width:40%}.lookup-form .gridInputs input{width:60%}.lookup-form .gridInputs,.lookup-form .gridInputs input,.lookup-form .gridInputs select{max-width:100%}.noMarginY{margin-top:0!important;margin-bottom:0!important}.placeholder,ng-select input:-moz-placeholder,ng-select input:-ms-input-placeholder,ng-select input:-webkit-input-placeholder,ng-select input:placeholder{color:#a9a9a9}select-dropdown div.options{text-align:left}.modal-dialog .modal-header .pull-right span{font-size:inherit!important}", ".file-container{font-size:medium}.file-container .file-list{display:flex;flex-direction:row;align-items:center;margin:2px;padding:0}.file-container .file-item{flex-grow:1;overflow:hidden;text-overflow:ellipsis;border-left:4px solid #009efb;padding-left:5px}.file-container .file-item .file-tools{float:right}.upload-drop-zone{border:1px dotted #d3d3d3;margin:0;padding:5px;background-color:#f5f5f5;align-items:center;text-align:center;color:#00f;cursor:pointer;position:relative}.upload-drop-zone.drop{color:#222}.upload-drop-zone.disabled{color:#ccc!important}.upload-drop-zone.disabled:focus{border:none!important}"]
                }] }
    ];
    /** @nocollapse */
    FVControlsUploadFileComponent.ctorParameters = function () { return [
        { type: ProcessService },
        { type: ApiService },
        { type: DGSNotificationService }
    ]; };
    FVControlsUploadFileComponent.propDecorators = {
        fileInput: [{ type: ViewChild, args: ['fileInput', { read: ViewContainerRef },] }]
    };
    return FVControlsUploadFileComponent;
}(FVAbstractControl));
export { FVControlsUploadFileComponent };
if (false) {
    /** @type {?} */
    FVControlsUploadFileComponent.prototype.isDragOver;
    /** @type {?} */
    FVControlsUploadFileComponent.prototype._files;
    /** @type {?} */
    FVControlsUploadFileComponent.prototype.fileInput;
    /** @type {?} */
    FVControlsUploadFileComponent.prototype.process;
    /** @type {?} */
    FVControlsUploadFileComponent.prototype.api;
    /** @type {?} */
    FVControlsUploadFileComponent.prototype.notification;
}

//# sourceMappingURL=data:application/json;base64, 