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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { I18N } from 'aurelia-i18n';
import { DialogController } from 'aurelia-dialog';
import { CustomLogger } from '../../modules/custom-logger';
import { Box } from '../../modules/box';
import { HttpClient } from 'aurelia-fetch-client';
import { bindable, autoinject, bindingMode } from 'aurelia-framework';
import { Config } from '../../config';
import { RemoteFileStorage } from './../../services/file-storage-service';
import { Layer } from 'konva/lib/Layer';
import { Stage } from 'konva/lib/Stage';
import { Image } from 'konva/lib/shapes/Image';
import { Group } from 'konva/lib/Group';
import { Line } from 'konva/lib/shapes/Line';
import { Text } from 'konva/lib/shapes/Text';
import { Transformer } from 'konva/lib/shapes/Transformer';
import { Node } from 'konva/lib/Node';
export var UIPictureEdit = (function () {
    function UIPictureEdit(box, i18n, config, httpClient, logger, dialogController, fileStorageService) {
        this.box = box;
        this.i18n = i18n;
        this.config = config;
        this.httpClient = httpClient;
        this.logger = logger;
        this.dialogController = dialogController;
        this.fileStorageService = fileStorageService;
        this.imageType = "url";
        this.isPainting = false;
        this.canDeleteElements = false;
        this.canPaint = false;
        this.isSaving = false;
    }
    UIPictureEdit.prototype.activate = function (params) {
        if (params != null) {
            this.imageUrl = params.url;
            if (params.type != null)
                this.imageType = params.type;
        }
    };
    UIPictureEdit.prototype.attached = function () {
        var _a, _b, _c;
        this.imageContainer.style.height = (((_c = (_b = (_a = this.imageContainer.parentElement) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.clientHeight) !== null && _c !== void 0 ? _c : 650) - 50) + "px";
        this.initKonva();
    };
    UIPictureEdit.prototype.detached = function () {
        if (this.canPaint) {
            this.onClickTogglePainting();
        }
        if (this.canDeleteElements) {
            this.onClickToggleDeleteElement();
        }
    };
    UIPictureEdit.prototype.initKonva = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.currentColor = "#000000";
                        this.currentLineStrokeWidth = 4;
                        this.stage = new Stage({
                            container: this.imageContainer,
                            width: this.imageContainer.clientWidth,
                            height: this.imageContainer.clientHeight
                        });
                        this.layer = new Layer();
                        this.stage.add(this.layer);
                        return [4, this.addBackgroundImage()];
                    case 1:
                        _a.sent();
                        return [4, this.addTransformer()];
                    case 2:
                        _a.sent();
                        this.stage.on("click", function (e) {
                            if (_this.canDeleteElements) {
                                return;
                            }
                            if (e.target === e.target.getStage()) {
                                _this.selectedNode = null;
                                _this.updateTransformer();
                                return;
                            }
                            _this.selectedNode = e.target;
                            _this.updateTransformer();
                        });
                        this.initHandDrawing();
                        this.initZooming();
                        return [2];
                }
            });
        });
    };
    UIPictureEdit.prototype.updateTransformer = function () {
        if (this.selectedNode === this.transformer.getNode()) {
            return;
        }
        if (this.selectedNode != null && this.selectedNode != this.imageGroup && this.selectedNode != this.image) {
            this.transformer.nodes([this.selectedNode]);
        }
        else {
            this.transformer.nodes([]);
        }
    };
    UIPictureEdit.prototype.findNodes = function (fromNode, name) {
        var _this = this;
        var _a;
        if (fromNode) {
            if (fromNode.className == name || ((_a = fromNode.attrs) === null || _a === void 0 ? void 0 : _a.className) == name)
                return [fromNode];
            if (fromNode.children && fromNode.children.length) {
                var founds_1 = [];
                fromNode.children.forEach(function (n) {
                    var found = _this.findNodes(n, name);
                    if (found != null)
                        founds_1 = founds_1.concat(found);
                });
                if (founds_1.length)
                    return founds_1;
            }
        }
    };
    UIPictureEdit.prototype.resetZoom = function () {
        this.stage.scale({ x: 1, y: 1 });
        this.stage.position({ x: 0, y: 0 });
    };
    UIPictureEdit.prototype.centerImageGroup = function () {
        if (this.imageGroup != null) {
            this.centerNode(this.imageGroup);
        }
    };
    UIPictureEdit.prototype.toggleImageGroupDraggable = function (state) {
        var _this = this;
        if (state === void 0) { state = null; }
        if (this.imageGroup.draggable() === false || state === true) {
            this.imageGroup.draggable(true);
            this.imageGroup.on('mouseenter', function () { _this.stage.container().style.cursor = 'grab'; });
            this.imageGroup.on('mouseleave', function () { _this.stage.container().style.cursor = 'default'; });
        }
        else {
            this.imageGroup.draggable(false);
            this.imageGroup.removeEventListener('mouseenter');
            this.imageGroup.removeEventListener('mouseleave');
        }
    };
    UIPictureEdit.prototype.addBackgroundImage = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                        var fileUrl;
                        var _this = this;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    if (!(this.imageUrl != null)) return [3, 2];
                                    this.imageGroup = new Group({
                                        x: 0,
                                        y: 0,
                                        width: this.stage.getSize().width,
                                        height: this.stage.getSize().height
                                    });
                                    this.toggleImageGroupDraggable(true);
                                    this.stage.on('dblclick dbltap', function (e) {
                                        e.evt.preventDefault();
                                        if (!(e.target instanceof Stage) && !(e.target instanceof Image))
                                            return;
                                        _this.resetZoom();
                                        _this.centerImageGroup();
                                    });
                                    this.layer.add(this.imageGroup);
                                    return [4, this.fileStorageService.fileUrl(this.imageUrl)];
                                case 1:
                                    fileUrl = _a.sent();
                                    Image.fromURL(fileUrl, function (img) {
                                        _this.image = img;
                                        _this.imageGroup.setSize(img.getSize());
                                        _this.imageGroup.add(img);
                                        _this.centerImageGroup();
                                        img.setZIndex(0.1);
                                    });
                                    _a.label = 2;
                                case 2:
                                    resolve(true);
                                    return [2];
                            }
                        });
                    }); })];
            });
        });
    };
    UIPictureEdit.prototype.addTransformer = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this.transformer = new Transformer({
                nodes: [],
                centeredScaling: true,
                rotationSnaps: [0, 90, 180, 270],
                resizeEnabled: true
            });
            _this.layer.add(_this.transformer);
            resolve(true);
        });
    };
    UIPictureEdit.prototype.centerNode = function (node) {
        if (node != null && node instanceof Node) {
            node.setAttrs({
                x: (this.stage.width() - node.width()) / 2,
                y: (this.stage.height() - node.height()) / 2
            });
        }
    };
    UIPictureEdit.prototype.setRemovable = function (node) {
        var _this = this;
        if (node != null && node instanceof Node) {
            var colorSave_1 = null;
            node.on('mouseenter', function () {
                if (_this.canDeleteElements) {
                    if (node instanceof Line) {
                        colorSave_1 = node.getAttr('stroke');
                        node.setAttr('stroke', 'blue');
                    }
                    else if (node instanceof Text) {
                        colorSave_1 = node.getAttr('fill');
                        node.setAttr('fill', 'blue');
                    }
                    else if (node instanceof Group) {
                        var rect = node.findOne('Rect');
                        if (rect) {
                            rect.setAttr('stroke', 'red');
                            rect.setAttr('strokeWidth', 5);
                        }
                        var img = node.findOne('Image');
                        if (img) {
                            img.setAttr('stroke', 'red');
                            img.setAttr('strokeWidth', 5);
                        }
                    }
                }
            });
            node.on('mouseleave', function () {
                if (_this.canDeleteElements) {
                    if (node instanceof Line) {
                        node.setAttr('stroke', colorSave_1 !== null && colorSave_1 !== void 0 ? colorSave_1 : _this.currentColor);
                    }
                    else if (node instanceof Text) {
                        node.setAttr('fill', colorSave_1 !== null && colorSave_1 !== void 0 ? colorSave_1 : _this.currentColor);
                    }
                    else if (node instanceof Group) {
                        var rect = node.findOne('Rect');
                        if (rect) {
                            rect.setAttr('stroke', 'black');
                            rect.setAttr('strokeWidth', 2);
                        }
                        var img = node.findOne('Image');
                        if (img) {
                            img.setAttr('strokeWidth', 0);
                        }
                    }
                }
            });
            node.on('click tap', function () {
                if (_this.canDeleteElements) {
                    node.remove();
                }
            });
        }
    };
    UIPictureEdit.prototype.initZooming = function () {
        var _this = this;
        var scaleBy = 1.2;
        this.stage.on('wheel', function (e) {
            if (!_this.isPainting) {
                e.evt.preventDefault();
                var oldScale = _this.stage.scaleX();
                var pointer = _this.stage.getPointerPosition();
                var mousePointTo = {
                    x: (pointer.x - _this.stage.x()) / oldScale,
                    y: (pointer.y - _this.stage.y()) / oldScale,
                };
                var newScale = e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy;
                _this.stage.scale({ x: newScale, y: newScale });
                var newPos = {
                    x: pointer.x - mousePointTo.x * newScale,
                    y: pointer.y - mousePointTo.y * newScale,
                };
                _this.stage.position(newPos);
            }
        });
    };
    UIPictureEdit.prototype.initHandDrawing = function () {
        var _this = this;
        var lastLine;
        this.stage.on('mousedown touchstart', function () {
            if (_this.canPaint) {
                _this.stage.container().style.cursor = 'crosshair';
                _this.isPainting = true;
                var pos = _this.stage.getPointerPosition();
                var pos2 = _this.stage.getPosition();
                lastLine = new Line({
                    stroke: _this.currentColor,
                    strokeWidth: parseInt(_this.currentLineStrokeWidth),
                    points: [(pos.x - pos2.x) / _this.stage.scaleX() - _this.imageGroup.x(), (pos.y - pos2.y) / _this.stage.scaleY() - _this.imageGroup.y()],
                    draggable: true
                });
                _this.insertLine(lastLine);
                lastLine.setZIndex(1);
            }
        });
        this.stage.on('mouseup touchend', function () {
            _this.isPainting = false;
            _this.stage.container().style.cursor = 'default';
        });
        this.stage.on('mousemove touchmove', function () {
            if (!_this.isPainting || !_this.canPaint) {
                return;
            }
            _this.stage.container().style.cursor = 'crosshair';
            var pos = _this.stage.getPointerPosition();
            var pos2 = _this.stage.getPosition();
            var newPoints = lastLine.points().concat([((pos.x - pos2.x) / _this.stage.scaleX()) - _this.imageGroup.x(), ((pos.y - pos2.y) / _this.stage.scaleY()) - _this.imageGroup.y()]);
            lastLine.points(newPoints);
        });
    };
    UIPictureEdit.prototype.insertLine = function (lineNode) {
        var _this = this;
        lineNode.on('mouseenter', function () {
            if (!_this.isPainting) {
                _this.stage.container().style.cursor = 'move';
            }
        });
        lineNode.on('mouseleave', function () {
            _this.stage.container().style.cursor = 'default';
        });
        this.setRemovable(lineNode);
        this.imageGroup.add(lineNode);
    };
    UIPictureEdit.prototype.onClickAddText = function () {
        return __awaiter(this, void 0, void 0, function () {
            var textString, text;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.canDeleteElements)
                            this.onClickToggleDeleteElement();
                        if (this.canPaint)
                            this.onClickTogglePainting();
                        textString = null;
                        return [4, this.box.showInput('Text', 'Text').whenClosed(function (closeResult) {
                                if (!closeResult.wasCancelled) {
                                    textString = closeResult.output;
                                }
                            })];
                    case 1:
                        _a.sent();
                        if (textString != null) {
                            text = new Text({
                                align: 'center',
                                verticalAlign: 'middle',
                                text: textString,
                                fill: this.currentColor,
                                fontSize: 20,
                                padding: 10,
                                draggable: true
                            });
                            this.setRemovable(text);
                            this.imageGroup.add(text);
                        }
                        return [2];
                }
            });
        });
    };
    UIPictureEdit.prototype.onClickRecenter = function () {
        this.resetZoom();
        this.centerImageGroup();
    };
    UIPictureEdit.prototype.onClickSave = function () {
        return __awaiter(this, void 0, void 0, function () {
            var base64, newImageUrl;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.canDeleteElements)
                            this.onClickToggleDeleteElement();
                        if (this.canPaint)
                            this.onClickTogglePainting();
                        this.onClickRecenter();
                        if (this.selectedNode != null) {
                            this.selectedNode = null;
                            this.updateTransformer();
                        }
                        this.isSaving = true;
                        base64 = this.imageGroup.toDataURL();
                        if (!(this.imageType == "url")) return [3, 2];
                        return [4, this.fileStorageService.uploadBase64(this.imageUrl, base64)];
                    case 1:
                        newImageUrl = _a.sent();
                        this.isSaving = false;
                        if (newImageUrl != null) {
                            this.logger.Log(this.i18n.tr("general.successfullySaved", { ns: "common" }), this.imageUrl, null, true);
                            this.dialogController.ok(newImageUrl);
                        }
                        else {
                            this.logger.LogError(this.i18n.tr("general.error", { ns: "common" }), this.imageUrl, null, true);
                        }
                        return [3, 3];
                    case 2:
                        this.dialogController.ok(base64);
                        _a.label = 3;
                    case 3: return [2];
                }
            });
        });
    };
    UIPictureEdit.prototype.onClickToggleDeleteElement = function () {
        var _this = this;
        if (this.canPaint)
            this.onClickTogglePainting();
        this.canDeleteElements = !this.canDeleteElements;
        if (this.canDeleteElements) {
            this.selectedNode = null;
            this.updateTransformer();
            this.stage.on('mouseenter', function () { _this.stage.container().style.cursor = 'crosshair !important'; });
            this.stage.on('mouseleave', function () { _this.stage.container().style.cursor = 'default'; });
        }
    };
    UIPictureEdit.prototype.onClickTogglePainting = function () {
        if (this.canDeleteElements)
            this.onClickToggleDeleteElement();
        this.canPaint = !this.canPaint;
        if (this.canPaint) {
            this.toggleImageGroupDraggable(false);
        }
        else {
            this.toggleImageGroupDraggable(true);
        }
    };
    UIPictureEdit.prototype.onClickZoomIn = function () {
        var oldX = this.stage.scaleX();
        var oldY = this.stage.scaleY();
        this.stage.scale({ x: (oldX * 1.2), y: (oldY * 1.2) });
    };
    UIPictureEdit.prototype.onClickZoomOut = function () {
        var oldX = this.stage.scaleX();
        var oldY = this.stage.scaleY();
        this.stage.scale({ x: (oldX * .8), y: (oldY * .8) });
    };
    UIPictureEdit.prototype.setLineWidth = function (width) {
        this.currentLineStrokeWidth = width;
    };
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UIPictureEdit.prototype, "imageUrl", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UIPictureEdit.prototype, "imageType", void 0);
    UIPictureEdit = __decorate([
        autoinject,
        __metadata("design:paramtypes", [Box, I18N, Config, HttpClient, CustomLogger, DialogController, RemoteFileStorage.Service])
    ], UIPictureEdit);
    return UIPictureEdit;
}());

//# sourceMappingURL=ui-picture-edit.js.map
