const direction = (game, account, source, target) => {
    const playerTeam = game.players.find(t => t.id === account.id);
    const playerTeamIds = playerTeam.constructs.map(c => c.id);
    const otherTeam = game.players.find(t => t.id !== account.id);
    const otherTeamIds = otherTeam.constructs.map(c => c.id);
    const sourceIsPlayer = playerTeamIds.includes(source);
    const targetIsPlayer = playerTeamIds.includes(target);

    const sameTeam = (sourceIsPlayer && targetIsPlayer) || (!sourceIsPlayer && !targetIsPlayer);
    let y = 0;
    if (!sameTeam) y = targetIsPlayer ? 1 : -1;

    const i = sourceIsPlayer
        ? playerTeamIds.findIndex(c => c === source)
        : otherTeamIds.findIndex(c => c === source);

    const j = targetIsPlayer
        ? playerTeamIds.findIndex(c => c === target)
        : otherTeamIds.findIndex(c => c === target);
    const x = j - i;
    return { x, y };
};


function getAnimSource(resolution, game, account) {
    const { source, target } = resolution.cast;
    const animSource = {
        animation: 'sourceCast',
        constructId: source,
        direction: direction(game, account, source, target),
    };
    return animSource;
}

function getAnimTarget(resolution, game, account) {
    const { source, target, skill } = resolution.cast;
    const player = resolution.cast.player === account;
    const animTarget = {
        constructId: resolution.cast.target,
        player,
        direction: direction(game, account, source, target),
        skill,
    };

    return animTarget;
}

function getFocusTargets(resolution, game, account) {
    if (resolution.variant[1] === 'AoeHit') {
        const playerTeam = game.players.find(t => t.id === account.id);
        const playerTeamIds = playerTeam.constructs.map(c => c.id);
        const otherTeam = game.players.find(t => t.id !== account.id);
        const otherTeamIds = otherTeam.constructs.map(c => c.id);
        if (resolution.cast.player === account) return playerTeamIds;
        return otherTeamIds;
    }

    const { source, target } = resolution.cast;
    return [source, target];
}

module.exports = {
    getAnimSource,
    getAnimTarget,
    getFocusTargets,
};
