import { HostListener, ViewChildren, QueryList, ChangeDetectorRef, ElementRef, Directive, inject } from '@angular/core';
import { nameof } from '@jscrpt/common';
import { Subject } from 'rxjs';
import { RelationNodeOutputSAComponent } from './relationsNodeOutput/relationsNodeOutput.component';
import { RelationNodeInputSAComponent } from './relationsNodeInput/relationsNodeInput.component';
import { RELATIONS_HISTORY_MANAGER } from '../misc/tokens';
import * as i0 from "@angular/core";
/**
 * Base class for relations node components
 */
export class RelationsNodeBase {
    /**
     * @inheritdoc
     */
    get id() {
        var _a, _b;
        return (_b = (_a = this.metadata) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : '';
    }
    /**
     * @inheritdoc
     */
    get allOutputs() {
        return this.ɵAllOutputs;
    }
    /**
     * @inheritdoc
     */
    get inputs() {
        return this.ɵInputs;
    }
    /**
     * @inheritdoc
     */
    get outputs() {
        return this.ɵOutputs;
    }
    /**
     * @inheritdoc
     */
    get destroy() {
        return this.destroySubject.asObservable();
    }
    //######################### constructor #########################
    constructor(changeDetector, element) {
        this.changeDetector = changeDetector;
        this.element = element;
        /**
         * Metadata history manager
         */
        this.history = inject(RELATIONS_HISTORY_MANAGER);
        /**
         * Indication whether is node initialized
         */
        this.initialized = false;
        /**
         * Indication whether user is dragging
         */
        this.isDragging = false;
        /**
         * Indication whether user moved node during drag
         */
        this.moved = false;
        /**
         * Last mouse down position
         */
        this.lastMouseDownPosition = {
            x: 0,
            y: 0
        };
        /**
         * Node position on last mouse down event
         */
        this.lastMouseDownNodePosition = {
            x: 0,
            y: 0
        };
        /**
         * Node position
         */
        this.nodePosition = {
            x: 0,
            y: 0,
        };
        /**
         * Array of all available outputs
         */
        this.ɵAllOutputs = [];
        /**
         * Object storing inputs by their names
         */
        this.ɵInputs = {};
        /**
         * Object storing outputs by their names
         */
        this.ɵOutputs = {};
        /**
         * Subject used for destroying node by user
         */
        this.destroySubject = new Subject();
        //######################### public properties - implementation of RelationsNode #########################
        /**
         * @inheritdoc
         */
        this.zoomLevel = 1;
        this.element.nativeElement.classList.add('relations-node');
        this.updatePosition();
        this.observer = new ResizeObserver(() => this.updateRelations());
        this.observer.observe(this.element.nativeElement);
    }
    //######################### public methods - implementation of OnChanges #########################
    /**
     * Called when input value changes
     */
    ngOnChanges(changes) {
        var _a;
        //initial change of metadata
        if (nameof('metadata') in changes && this.metadata) {
            if ((_a = this.metadata.nodeMetadata) === null || _a === void 0 ? void 0 : _a.coordinates) {
                this.nodePosition = this.metadata.nodeMetadata.coordinates;
                this.updatePosition();
            }
            this.metadataSet();
        }
    }
    //######################### public methods - implementation of OnDestroy #########################
    /**
     * Called when component is destroyed
     */
    ngOnDestroy() {
        var _a;
        (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
    }
    //######################### public methods - implementation of RelationsNode #########################
    /**
     * @inheritdoc
     */
    invalidateVisuals() {
        this.changeDetector.detectChanges();
        if (!this.initialized) {
            this.initialized = true;
            this.initEndpoints();
        }
    }
    /**
     * @inheritdoc
     */
    initialize() {
    }
    //######################### protected methods methods - host listeners #########################
    /**
     * Mouse down event
     * @param event
     */
    onMouseDown(event) {
        this.moved = false;
        this.isDragging = true;
        this.lastMouseDownPosition =
            {
                x: event.clientX,
                y: event.clientY
            };
        this.lastMouseDownNodePosition =
            {
                x: this.nodePosition.x,
                y: this.nodePosition.y
            };
        event.stopImmediatePropagation();
    }
    /**
     * Mouse move event
     * @param event
     */
    onMouseMove(event) {
        if (this.isDragging) {
            this.moved = true;
            this.nodePosition =
                {
                    x: this.lastMouseDownNodePosition.x + (event.clientX - this.lastMouseDownPosition.x) * 1 / this.zoomLevel,
                    y: this.lastMouseDownNodePosition.y + (event.clientY - this.lastMouseDownPosition.y) * 1 / this.zoomLevel,
                };
            this.updatePosition();
            event.stopImmediatePropagation();
            event.preventDefault();
            this.updateRelations();
        }
    }
    /**
     * Mouse up event
     * @param event
     */
    onMouseUp(event) {
        if (this.isDragging) {
            if (this.moved) {
                this.history.getNewState();
            }
            this.isDragging = false;
            event.stopImmediatePropagation();
            event.preventDefault();
        }
    }
    //######################### protected methods #########################
    /**
     * Initialize endpoints
     */
    initEndpoints() {
        var _a, _b;
        const updateInputs = () => {
            var _a;
            this.ɵInputs = {};
            (_a = this.inputsChildren) === null || _a === void 0 ? void 0 : _a.forEach(input => {
                if (input.name) {
                    this.ɵInputs[input.name] = input;
                }
            });
            Object.freeze(this.ɵInputs);
        };
        const updateOutputs = () => {
            var _a;
            this.ɵAllOutputs = this.outputsChildren.toArray();
            this.ɵOutputs = {};
            (_a = this.outputsChildren) === null || _a === void 0 ? void 0 : _a.forEach(output => {
                if (output.name) {
                    this.ɵOutputs[output.name] = output;
                }
            });
            Object.freeze(this.ɵOutputs);
        };
        (_a = this.inputsChildren) === null || _a === void 0 ? void 0 : _a.changes.subscribe(() => updateInputs());
        (_b = this.outputsChildren) === null || _b === void 0 ? void 0 : _b.changes.subscribe(() => updateOutputs());
        updateInputs();
        updateOutputs();
    }
    /**
     * Updates node relations
     */
    updateRelations() {
        this.inputsChildren.forEach(input => {
            input.updateRelation();
        });
        this.outputsChildren.forEach(output => {
            output.updateRelation();
        });
    }
    /**
     * Updates node position
     */
    updatePosition() {
        var _a, _b;
        this.element.nativeElement.style.left = `${this.nodePosition.x}px`;
        this.element.nativeElement.style.top = `${this.nodePosition.y}px`;
        if ((_b = (_a = this.metadata) === null || _a === void 0 ? void 0 : _a.nodeMetadata) === null || _b === void 0 ? void 0 : _b.coordinates) {
            this.metadata.nodeMetadata.coordinates.x = this.nodePosition.x;
            this.metadata.nodeMetadata.coordinates.y = this.nodePosition.y;
        }
    }
    /**
     * Allows code to be called after metadata were set
     */
    metadataSet() {
    }
}
RelationsNodeBase.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: RelationsNodeBase, deps: [{ token: i0.ChangeDetectorRef }, { token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive });
RelationsNodeBase.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "17.0.4", type: RelationsNodeBase, host: { listeners: { "mousedown": "onMouseDown($event)", "window:mousemove": "onMouseMove($event)", "window:mouseup": "onMouseUp($event)" } }, viewQueries: [{ propertyName: "inputsChildren", predicate: RelationNodeInputSAComponent, descendants: true }, { propertyName: "outputsChildren", predicate: RelationNodeOutputSAComponent, descendants: true }], usesOnChanges: true, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: RelationsNodeBase, decorators: [{
            type: Directive
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }, { type: i0.ElementRef }], propDecorators: { inputsChildren: [{
                type: ViewChildren,
                args: [RelationNodeInputSAComponent]
            }], outputsChildren: [{
                type: ViewChildren,
                args: [RelationNodeOutputSAComponent]
            }], onMouseDown: [{
                type: HostListener,
                args: ['mousedown', ['$event']]
            }], onMouseMove: [{
                type: HostListener,
                args: ['window:mousemove', ['$event']]
            }], onMouseUp: [{
                type: HostListener,
                args: ['window:mouseup', ['$event']]
            }] } });
//# sourceMappingURL=relationsNodeBase.js.map