import * as React from "react";
import {RountangleState} from "./RountangleComponent";
import {PrimitiveValue} from "../../onion/types";

interface RountangleResizeHandleProps {
    id:               PrimitiveValue;
    x:                number;
    y:                number;
    width:            number;
    height:           number;
    onResize:         (deltaX: number, deltaY: number) => void;
    onResizeComplete: () => void;
}

export interface RountangleResizeHandleState {
    dragging:     boolean;
    moved:        boolean;
}

export class RountangleResizeHandleComponent extends React.Component<RountangleResizeHandleProps, RountangleResizeHandleState> {
    shouldComponentUpdate(nextProps: Readonly<RountangleResizeHandleProps>, nextState: Readonly<RountangleState>, nextContext: any): boolean {
        return this.props.width !== nextProps.width
            || this.props.height !== nextProps.height
            || this.props.x !== nextProps.x
            || this.props.y !== nextProps.y
    }

    constructor(props: RountangleResizeHandleProps) {
        super(props);
        this.state = {
            dragging:    false,
            moved:       false
        }
    }

    onPointerDown = (event: React.PointerEvent<SVGSVGElement>) => {
        // only left mouse button
        if (event.button !== 0) return;

        event.currentTarget.setPointerCapture(event.pointerId);

        this.setState({
            dragging:       true,
            moved:          false
        });

        event.stopPropagation();
        event.preventDefault();
    }

    onPointerMove = (event: React.PointerEvent<SVGSVGElement>) => {
        if (!this.state.dragging) return;

        this.props.onResize(event.movementX, event.movementY);

        event.stopPropagation();
        event.preventDefault();
    }

    onPointerUp = (event: React.PointerEvent<SVGSVGElement>) => {
        event.currentTarget.releasePointerCapture(event.pointerId);
        event.stopPropagation();
        event.preventDefault();

        // if left button, complete dragging
        if (event.button === 0) {
            if (this.state.dragging) {
                this.setState({dragging: false, moved: false});
                this.props.onResizeComplete();
            }
        }
    }

    render() {
        return <svg
            x={this.props.x + this.props.width - 16.5}
            y={this.props.y + this.props.height - 16.5}
            width={15}
            height={15}
            className="re-rountangle-resize-handle"
            onPointerDown={this.onPointerDown}
            onPointerMove={this.onPointerMove}
            onPointerUp={this.onPointerUp}
        >
            <polygon
                points={"15,0 15,15, 0,15"}
            />
        </svg>
    }
}