import {Class, MedicState, PlayerState, WorldBoundaries} from "../Data/Parser";
import {Show} from "solid-js";

export interface HealBeamProp {
    player: PlayerState;
    mapBoundary: WorldBoundaries;
    targetSize: {
        width: number;
        height: number;
    };
    scale: number;
    players: PlayerState[];
}

export function HealBeam(props: HealBeamProp) {
    const worldWidth = props.mapBoundary.boundary_max.x - props.mapBoundary.boundary_min.x;
    const worldHeight = props.mapBoundary.boundary_max.y - props.mapBoundary.boundary_min.y;
    const scaleX = (x) => (x - props.mapBoundary.boundary_min.x) / worldWidth * props.targetSize.width;
    const scaleY = (y) => (worldHeight - (y - props.mapBoundary.boundary_min.y)) / worldHeight * props.targetSize.height;
    const scaledX = () => scaleX(props.player.position.x);
    const scaledY = () => scaleY(props.player.position.y);

    const targetPosition = () => {
        if (props.player.playerClass !== Class.Medic) {
            return null;
        }
        const target = (props.player.class_data as MedicState).target;
        if (target === 0) {
            return null;
        }
        for (let player of props.players) {
            if (player.info.entityId === target) {
                return {
                    x: scaleX(player.position.x),
                    y: scaleY(player.position.y),
                };
            }
        }
        return null;
    };
    const distance = () => Math.sqrt(Math.pow(Math.abs(scaledX() - targetPosition().x), 2) + Math.pow(Math.abs(scaledY() - targetPosition().y), 2));
    const aimHandle = () => {
        let angle = (270 - props.player.angle) / 360 * (Math.PI * 2);
        return {
            x: scaledX() - Math.sin(angle) * (distance() / 2),
            y: scaledY() + Math.cos(angle) * (distance() / 2)
        }
    }
    const aimStart = () => {
        let angle = (270 - props.player.angle) / 360 * (Math.PI * 2);
        return {
            x: scaledX() - Math.sin(angle) * (16 / props.scale),
            y: scaledY() + Math.cos(angle) * (16 / props.scale)
        }
    }

    const path = () => `M ${aimStart().x} ${aimStart().y} C ${aimHandle().x} ${aimHandle().y} ${aimHandle().x} ${aimHandle().y} ${targetPosition().x} ${targetPosition().y}`;

    return <g>
        <Show when={targetPosition()}>
            <path
                d={path()}
                fill="transparent" stroke="white" stroke-width={1.5 / props.scale}
            />
        </Show>
    </g>
}