const preact = require('preact');
const { connect } = require('preact-redux');

const addState = connect(
    ({ game, account, resolution }) => ({ game, account, resolution })
);

function TargetSvg(args) {
    const { game, account, resolution } = args;

    const playerTeam = game.players.find(t => t.id === account.id);
    const otherTeam = game.players.find(t => t.id !== account.id);

    const playerTeamIds = playerTeam.cryps.map(c => c.id);
    const outgoing = game.stack.filter(stack => playerTeamIds.includes(stack.source_cryp_id));

    function getPath(cast) {
        const source = playerTeam.cryps.findIndex(c => c.id === cast.source_cryp_id);
        const defensive = playerTeamIds.includes(cast.target_cryp_id);
        const target = defensive
            ? playerTeam.cryps.findIndex(c => c.id === cast.target_cryp_id)
            : otherTeam.cryps.findIndex(c => c.id === cast.target_cryp_id);

        const skillIndex = playerTeam.cryps[source].skills.findIndex(s => s.skill === cast.skill);

        const skillOffset = (100 * skillIndex) + 50;
        const sourceY = 0;
        const sourceX = (source * 300) + skillOffset;
        const targetY = (target * 300) + 150;
        const curveStart = 150 + (150 * source);
        const curveEnd = 450 + curveStart;

        if (defensive) {
            const path = `
                M${sourceX},${sourceY}
                L${sourceY},150
                C${sourceY},150 ${targetY},150 ${targetY},150
                L${targetY},0
                L${targetY - 4},50
                M${targetY},0
                L${targetY + 4},0
            `;

            return <path d={path} />;
        }

        const path = `
            M${sourceX},${sourceY}
            L${curveStart},${sourceY}
            C${curveEnd},${sourceY} ${curveStart},${targetY} ${curveEnd},${targetY}
            L${targetY},900
            L${targetY - 4},850
            M${targetY},900
            L${targetY + 4},850
        `;

        return <path d={path} />;
    }

    const arrows = resolution
        ? null
        : outgoing.map(getPath);

    return (
        <svg preserveAspectRatio="none" className="targeting-arrows">
            {arrows}
        </svg>
    );
}

module.exports = addState(TargetSvg);
