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 sourceX = 0;
        const sourceY = (source * 300) + skillOffset;
        const targetY = (target * 300) + 150;
        const curveStart = 150 + (150 * source);
        const curveEnd = 450 + curveStart;

        if (defensive) {
            const path = `
                M${sourceX},${sourceY}
                L150,${sourceY}
                C150,${sourceY} 150,${targetY} 150,${targetY}
                L0,${targetY}
                L50,${targetY - 4}
                M0,${targetY}
                L50,${targetY + 4}
            `;

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

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

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

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

    return (
        <svg viewBox="0 0 900 900" preserveAspectRatio="none" className="target-svg">
            {arrows}
        </svg>
    );
}

module.exports = addState(TargetSvg);
