import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { EventEmitter, Component, Input, Output, NgModule } from '@angular/core';
import { fabric } from 'fabric';

/**
 * @license
 * Copyright ASW (A Software World) All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file
 */
class AswImageDrawingComponent {
    constructor() {
        this.forceSizeCanvas = true;
        this.forceSizeExport = false;
        this.enableRemoveImage = false;
        this.enableLoadAnotherImage = false;
        this.enableTooltip = true;
        this.showCancelButton = true;
        /* @deprecated Use i18n.saveBtn */
        this.saveBtnText = 'Save';
        /* @deprecated Use i18n.cancelBtn */
        this.cancelBtnText = 'Cancel';
        /* @deprecated Use i18n.loading */
        this.loadingText = 'Loading…';
        this.outputMimeType = 'image/jpeg';
        this.outputQuality = 0.8;
        // @Input() public borderCss = 'none';
        this.drawingSizes = {
            small: 5,
            medium: 10,
            large: 25,
        };
        this.colors = {
            black: '#000',
            white: '#fff',
            yellow: '#ffeb3b',
            red: '#f44336',
            blue: '#2196f3',
            green: '#4caf50',
            purple: '#7a08af',
        };
        this.save = new EventEmitter();
        this.cancel = new EventEmitter();
        this.currentTool = 'brush';
        this.currentSize = 'small';
        this.currentColor = 'black';
        // public i18n: I18nInterface = I18nEn;
        this.canUndo = false;
        this.canRedo = false;
        this.isLoading = false;
        this.hasError = false;
        this.errorMessage = '';
        this.stack = [];
        this.colorsName = [];
        this.drawingSizesName = [];
    }
    ngOnInit() {
        this.colorsName = Object.keys(this.colors);
        this.drawingSizesName = Object.keys(this.drawingSizes);
        this.canvas = new fabric.Canvas('canvas', {
            hoverCursor: 'pointer',
            isDrawingMode: true
        });
        this.canvas.backgroundColor = 'white';
        if (this.src) {
            this.importPhotoFromSrc(this.src);
        }
        else {
            if (!this.width || !this.height) {
                throw new Error('No width or hight given !');
            }
            this.canvas.setWidth(this.width);
            this.canvas.setHeight(this.height);
        }
        this.canvas.on('path:created', () => {
            this.stack = [];
            this.setUndoRedo();
        });
        this.selectTool(this.currentTool);
        this.selectColor(this.currentColor);
        this.selectDrawingSize(this.currentSize);
    }
    // Tools
    selectTool(tool) {
        this.currentTool = tool;
    }
    selectDrawingSize(size) {
        this.currentSize = size;
        if (this.canvas) {
            this.canvas.freeDrawingBrush.width = this.drawingSizes[size];
        }
    }
    selectColor(color) {
        this.currentColor = color;
        if (this.canvas) {
            this.canvas.freeDrawingBrush.color = this.colors[color];
        }
    }
    // Actions
    undo() {
        if (this.canUndo) {
            const lastId = this.canvas.getObjects().length - 1;
            const lastObj = this.canvas.getObjects()[lastId];
            this.stack.push(lastObj);
            this.canvas.remove(lastObj);
            this.setUndoRedo();
        }
    }
    redo() {
        if (this.canRedo) {
            const firstInStack = this.stack.splice(-1, 1)[0];
            if (firstInStack) {
                this.canvas.insertAt(firstInStack, this.canvas.getObjects().length - 1, false);
            }
            this.setUndoRedo();
        }
    }
    clearCanvas() {
        if (this.canvas) {
            this.canvas.remove(...this.canvas.getObjects());
            this.setUndoRedo();
        }
    }
    saveImage() {
        this.canvas.getElement().toBlob((data) => {
            this.save.emit(data);
        }, this.outputMimeType, this.outputQuality);
    }
    cancelAction() {
        this.cancel.emit();
    }
    setUndoRedo() {
        this.canUndo = this.canvas.getObjects().length > 0;
        this.canRedo = this.stack.length > 0;
        // this.canvas.renderAll();
    }
    importPhotoFromFile(event) {
        if (event.target.files && event.target.files.length > 0) {
            const file = event.target.files[0];
            if (file.type.match('image.*')) {
                this.importPhotoFromBlob(file);
            }
            else {
                throw new Error('Not an image !');
            }
        }
    }
    removeImage() {
        if (this.imageUsed) {
            this.imageUsed.dispose();
            this.imageUsed = null;
        }
        this.canvas.backgroundImage = null;
        if (this.width && this.height) {
            this.canvas.setWidth(this.width);
            this.canvas.setHeight(this.height);
        }
        this.canvas.renderAll();
    }
    get hasImage() {
        return !!this.canvas.backgroundImage;
    }
    importPhotoFromSrc(src) {
        this.isLoading = true;
        let isFirstTry = true;
        const imgEl = new Image();
        imgEl.setAttribute('crossOrigin', 'anonymous');
        imgEl.src = src;
        imgEl.onerror = () => {
            // Retry with cors proxy
            if (isFirstTry) {
                imgEl.src = 'https://cors-anywhere.herokuapp.com/' + this.src;
                isFirstTry = false;
            }
            else {
                this.isLoading = false;
                this.hasError = true;
                // this.errorMessage = this.getTextTranslated('loadError').replace('%@', this.src as string);
            }
        };
        imgEl.onload = () => {
            this.isLoading = false;
            this.imageUsed = new fabric.Image(imgEl);
            this.imageUsed.cloneAsImage((image) => {
                let width = imgEl.width;
                let height = imgEl.height;
                const ratio = (640 / width < 480 / height
                    ? 640 / width
                    : 480 / width);
                width = width * ratio;
                height = height * ratio;
                image.scaleToWidth(width, false);
                image.scaleToHeight(height, false);
                this.canvas.setBackgroundImage(image, ((img) => {
                    if (img) {
                        if (this.forceSizeCanvas) {
                            this.canvas.setWidth(width);
                            this.canvas.setHeight(height);
                        }
                        else {
                            this.canvas.setWidth(image.getScaledWidth());
                            this.canvas.setHeight(image.getScaledHeight());
                        }
                    }
                }), {
                    crossOrigin: 'anonymous',
                    originX: 'left',
                    originY: 'top'
                });
            });
        };
    }
    importPhotoFromBlob(file) {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (evtReader) => {
            if (evtReader.target.readyState === FileReader.DONE) {
                this.importPhotoFromSrc(evtReader.target.result);
            }
        };
    }
    ngOnChanges(changes) {
        if (changes.src && !changes.src.firstChange && changes.src.currentValue) {
            if (typeof changes.src.currentValue === 'string') {
                this.importPhotoFromSrc(changes.src.currentValue);
            }
            else if (changes.src.currentValue instanceof Blob) {
                this.importPhotoFromBlob(changes.src.currentValue);
            }
        }
    }
}
AswImageDrawingComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: AswImageDrawingComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
AswImageDrawingComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.2.4", type: AswImageDrawingComponent, selector: "asw-image-drawing", inputs: { src: "src", width: "width", height: "height", forceSizeCanvas: "forceSizeCanvas", forceSizeExport: "forceSizeExport", enableRemoveImage: "enableRemoveImage", enableLoadAnotherImage: "enableLoadAnotherImage", enableTooltip: "enableTooltip", showCancelButton: "showCancelButton", saveBtnText: "saveBtnText", cancelBtnText: "cancelBtnText", loadingText: "loadingText", loadingTemplate: "loadingTemplate", errorTemplate: "errorTemplate", outputMimeType: "outputMimeType", outputQuality: "outputQuality", drawingSizes: "drawingSizes", colors: "colors" }, outputs: { save: "save", cancel: "cancel" }, usesOnChanges: true, ngImport: i0, template: "<div class=\"asw-drawing-card\">\r\n    <div class=\"loading\" *ngIf=\"isLoading\">\r\n        <ng-container *ngTemplateOutlet=\"loadingTemplate ? loadingTemplate : defaultLoading\"></ng-container>\r\n    </div>\r\n    <div class=\"error\" *ngIf=\"hasError\">\r\n        <ng-container *ngTemplateOutlet=\"errorTemplate ? errorTemplate : defaultError\"></ng-container>\r\n    </div>\r\n    \r\n    <ng-template #defaultLoading><p>{{ loadingText }}</p></ng-template>\r\n    <ng-template #defaultError> <p>{{ errorMessage }}</p> </ng-template>\r\n        \r\n    <div class=\"asw-drawing\">\r\n        <canvas id=\"canvas\" class=\"asw-drawing-canvas\"></canvas>\r\n    </div>\r\n    <div class=\"toolbar\" *ngIf=\"!isLoading\">\r\n        <div class=\"tools\">\r\n            <div class=\"row\">\r\n                <div class=\"col-md-12\">\r\n                    <i class=\"material-icons btn-selector\" \r\n                        [class.selected]=\"currentTool == 'brush'\" \r\n                        (click)=\"selectTool('brush')\"\r\n                        title=\"Brush\">brush</i>\r\n                    <span *ngFor=\"let drawingSizeName of drawingSizesName\" \r\n                            class=\"size btn-selector\"\r\n                            [style.width.px]=\"drawingSizes[drawingSizeName] * 0.8 + 8\"\r\n                            [style.height.px]=\"drawingSizes[drawingSizeName] * 0.8 + 8\"\r\n                            [style.borderRadius.px]=\"drawingSizes[drawingSizeName] * 0.4 + 4\"\r\n                            [class.selected]=\"currentSize == drawingSizeName\"\r\n                            title=\"{{drawingSizeName}}\"\r\n                            (click)=\"selectDrawingSize(drawingSizeName)\">\r\n                    </span>\r\n        \r\n                    <input style=\"display: none\" \r\n                            type=\"file\" \r\n                            #fileInput \r\n                            (change)=\"importPhotoFromFile($event)\"\r\n                            accept=\"image/*\"/>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        *ngIf=\"enableLoadAnotherImage && !hasImage\" \r\n                        (click)=\"fileInput.click();\"\r\n                        title=\"Load image\">attach_file\r\n                    </i>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        *ngIf=\"enableRemoveImage && hasImage\" \r\n                        (click)=\"removeImage()\"\r\n                        title=\"Remove image\">clear</i>\r\n        \r\n                    <i class=\"material-icons btn-selector\" \r\n                        [class.disabled]=\"!canUndo\" \r\n                        (click)=\"undo()\"\r\n                        title=\"Undo\">undo</i>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        [class.disabled]=\"!canRedo\" \r\n                        (click)=\"redo()\"\r\n                        title=\"Redo\">redo</i>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        (click)=\"clearCanvas()\" \r\n                        title=\"Clear\">delete</i>\r\n                </div>\r\n            </div>\r\n            <div class=\"row\">\r\n                <div *ngFor=\"let colorName of colorsName\" \r\n                        [class.selected]=\"currentColor == colorName\" \r\n                        class=\"color\"\r\n                        [ngClass]=\"colorName\"\r\n                        [style.background]=\"colors[colorName]\" \r\n                        title=\"{{colorName}}\"\r\n                        (click)=\"selectColor(colorName)\">\r\n                </div>\r\n            </div>\r\n        </div>\r\n        <div class=\"buttons\">\r\n            <a href=\"#\" \r\n                class=\"btn btn-primary\"\r\n                (click)=\"saveImage(); $event.preventDefault()\">Save</a>\r\n            <a href=\"#\" \r\n                class=\"btn btn-light\" \r\n                *ngIf=\"showCancelButton\"\r\n                (click)=\"cancelAction(); $event.preventDefault()\">Cancel</a>\r\n        </div>\r\n        <!-- Any additional toolbar buttons to be projected by the consuming app -->\r\n        <ng-content></ng-content>\r\n    </div>\r\n</div>\r\n", styles: [":host .asw-drawing-card{display:flex;flex-flow:column;align-items:center}:host .asw-drawing{flex:1;margin:1em auto auto}:host .asw-drawing-canvas{border:1.5px #d6d6d6 dashed;border-radius:7px}:host .size{background-color:#000;display:inline-block;margin:.2rem}:host .size.selected{background-color:#bdbdbd}:host .btn{cursor:pointer}:host .btn.selected{color:#bdbdbd}:host .btn.disabled{cursor:initial;color:#bdbdbd}:host .color{width:28px;height:28px;border-radius:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;margin:.2rem}:host .color.selected:after{content:\"\";width:10px;height:10px;background:#000;display:flex;border-radius:5px}:host .color.black{background-color:#000}:host .color.black.selected:after{background:#fff}:host .color.white{border:1px solid #a7a7a7}\n"], directives: [{ type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet"] }, { type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: AswImageDrawingComponent, decorators: [{
            type: Component,
            args: [{ selector: 'asw-image-drawing', template: "<div class=\"asw-drawing-card\">\r\n    <div class=\"loading\" *ngIf=\"isLoading\">\r\n        <ng-container *ngTemplateOutlet=\"loadingTemplate ? loadingTemplate : defaultLoading\"></ng-container>\r\n    </div>\r\n    <div class=\"error\" *ngIf=\"hasError\">\r\n        <ng-container *ngTemplateOutlet=\"errorTemplate ? errorTemplate : defaultError\"></ng-container>\r\n    </div>\r\n    \r\n    <ng-template #defaultLoading><p>{{ loadingText }}</p></ng-template>\r\n    <ng-template #defaultError> <p>{{ errorMessage }}</p> </ng-template>\r\n        \r\n    <div class=\"asw-drawing\">\r\n        <canvas id=\"canvas\" class=\"asw-drawing-canvas\"></canvas>\r\n    </div>\r\n    <div class=\"toolbar\" *ngIf=\"!isLoading\">\r\n        <div class=\"tools\">\r\n            <div class=\"row\">\r\n                <div class=\"col-md-12\">\r\n                    <i class=\"material-icons btn-selector\" \r\n                        [class.selected]=\"currentTool == 'brush'\" \r\n                        (click)=\"selectTool('brush')\"\r\n                        title=\"Brush\">brush</i>\r\n                    <span *ngFor=\"let drawingSizeName of drawingSizesName\" \r\n                            class=\"size btn-selector\"\r\n                            [style.width.px]=\"drawingSizes[drawingSizeName] * 0.8 + 8\"\r\n                            [style.height.px]=\"drawingSizes[drawingSizeName] * 0.8 + 8\"\r\n                            [style.borderRadius.px]=\"drawingSizes[drawingSizeName] * 0.4 + 4\"\r\n                            [class.selected]=\"currentSize == drawingSizeName\"\r\n                            title=\"{{drawingSizeName}}\"\r\n                            (click)=\"selectDrawingSize(drawingSizeName)\">\r\n                    </span>\r\n        \r\n                    <input style=\"display: none\" \r\n                            type=\"file\" \r\n                            #fileInput \r\n                            (change)=\"importPhotoFromFile($event)\"\r\n                            accept=\"image/*\"/>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        *ngIf=\"enableLoadAnotherImage && !hasImage\" \r\n                        (click)=\"fileInput.click();\"\r\n                        title=\"Load image\">attach_file\r\n                    </i>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        *ngIf=\"enableRemoveImage && hasImage\" \r\n                        (click)=\"removeImage()\"\r\n                        title=\"Remove image\">clear</i>\r\n        \r\n                    <i class=\"material-icons btn-selector\" \r\n                        [class.disabled]=\"!canUndo\" \r\n                        (click)=\"undo()\"\r\n                        title=\"Undo\">undo</i>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        [class.disabled]=\"!canRedo\" \r\n                        (click)=\"redo()\"\r\n                        title=\"Redo\">redo</i>\r\n                    <i class=\"material-icons btn-selector\" \r\n                        (click)=\"clearCanvas()\" \r\n                        title=\"Clear\">delete</i>\r\n                </div>\r\n            </div>\r\n            <div class=\"row\">\r\n                <div *ngFor=\"let colorName of colorsName\" \r\n                        [class.selected]=\"currentColor == colorName\" \r\n                        class=\"color\"\r\n                        [ngClass]=\"colorName\"\r\n                        [style.background]=\"colors[colorName]\" \r\n                        title=\"{{colorName}}\"\r\n                        (click)=\"selectColor(colorName)\">\r\n                </div>\r\n            </div>\r\n        </div>\r\n        <div class=\"buttons\">\r\n            <a href=\"#\" \r\n                class=\"btn btn-primary\"\r\n                (click)=\"saveImage(); $event.preventDefault()\">Save</a>\r\n            <a href=\"#\" \r\n                class=\"btn btn-light\" \r\n                *ngIf=\"showCancelButton\"\r\n                (click)=\"cancelAction(); $event.preventDefault()\">Cancel</a>\r\n        </div>\r\n        <!-- Any additional toolbar buttons to be projected by the consuming app -->\r\n        <ng-content></ng-content>\r\n    </div>\r\n</div>\r\n", styles: [":host .asw-drawing-card{display:flex;flex-flow:column;align-items:center}:host .asw-drawing{flex:1;margin:1em auto auto}:host .asw-drawing-canvas{border:1.5px #d6d6d6 dashed;border-radius:7px}:host .size{background-color:#000;display:inline-block;margin:.2rem}:host .size.selected{background-color:#bdbdbd}:host .btn{cursor:pointer}:host .btn.selected{color:#bdbdbd}:host .btn.disabled{cursor:initial;color:#bdbdbd}:host .color{width:28px;height:28px;border-radius:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;margin:.2rem}:host .color.selected:after{content:\"\";width:10px;height:10px;background:#000;display:flex;border-radius:5px}:host .color.black{background-color:#000}:host .color.black.selected:after{background:#fff}:host .color.white{border:1px solid #a7a7a7}\n"] }]
        }], ctorParameters: function () { return []; }, propDecorators: { src: [{
                type: Input
            }], width: [{
                type: Input
            }], height: [{
                type: Input
            }], forceSizeCanvas: [{
                type: Input
            }], forceSizeExport: [{
                type: Input
            }], enableRemoveImage: [{
                type: Input
            }], enableLoadAnotherImage: [{
                type: Input
            }], enableTooltip: [{
                type: Input
            }], showCancelButton: [{
                type: Input
            }], saveBtnText: [{
                type: Input
            }], cancelBtnText: [{
                type: Input
            }], loadingText: [{
                type: Input
            }], loadingTemplate: [{
                type: Input
            }], errorTemplate: [{
                type: Input
            }], outputMimeType: [{
                type: Input
            }], outputQuality: [{
                type: Input
            }], drawingSizes: [{
                type: Input
            }], colors: [{
                type: Input
            }], save: [{
                type: Output
            }], cancel: [{
                type: Output
            }] } });

/**
 * @license
 * Copyright ASW (A Software World) All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file
 */
class AswImageDrawingModule {
}
AswImageDrawingModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: AswImageDrawingModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
AswImageDrawingModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: AswImageDrawingModule, declarations: [AswImageDrawingComponent], imports: [CommonModule], exports: [AswImageDrawingComponent] });
AswImageDrawingModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: AswImageDrawingModule, imports: [[
            CommonModule
        ]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.2.4", ngImport: i0, type: AswImageDrawingModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [
                        AswImageDrawingComponent
                    ],
                    exports: [
                        AswImageDrawingComponent,
                    ],
                    imports: [
                        CommonModule
                    ]
                }]
        }] });

/**
 * @license
 * Copyright ASW (A Software World) All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file
 */

/**
 * Generated bundle index. Do not edit.
 */

export { AswImageDrawingComponent, AswImageDrawingModule };
//# sourceMappingURL=asoftwareworld-form-builder-image-drawing.mjs.map
