package com.ghost.technic.server.board;

import com.ghost.technic.server.card.playable.usable.impl.CreatureCard;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.*;

@Data
@NoArgsConstructor
public class Battleline {
    private LinkedList<CreatureCard> creatures = new LinkedList<>();

    /**
     * Adds a creature to the specified flank (LEFT or RIGHT).
     */
    public void addToFlank(CreatureCard creature, Flank preferredFlank) {
        if (creatures.isEmpty()) {
            creatures.add(creature);
        } else {
            switch (preferredFlank) {
                case LEFT -> creatures.addFirst(creature);
                case RIGHT -> creatures.addLast(creature);
                default -> throw new IllegalArgumentException("Unknown flank: " + preferredFlank);
            }
        }
    }

    /**
     * Returns the immediate neighbors of the given creature in the battleline.
     */
    public List<CreatureCard> getNeighbors(CreatureCard creature) {
        int index = creatures.indexOf(creature);
        List<CreatureCard> neighbors = new ArrayList<>();

        if (index > 0) {
            neighbors.add(creatures.get(index - 1));
        }
        if (index >= 0 && index < creatures.size() - 1) {
            neighbors.add(creatures.get(index + 1));
        }

        return neighbors;
    }

    /**
     * Determines whether the creature is at the left or right flank.
     * First creature is considered both left and right flank.
     */
    public Set<Flank> getEffectiveFlanks(CreatureCard creature) {
        Set<Flank> flanks = new HashSet<>();
        int index = creatures.indexOf(creature);

        if (index == 0) {
            flanks.add(Flank.LEFT);
        }
        if (index == creatures.size() - 1) {
            flanks.add(Flank.RIGHT);
        }

        // If it’s the only creature, it’s left, right and center
        if (creatures.size() == 1 && index == 0) {
            flanks.add(Flank.LEFT);
            flanks.add(Flank.CENTER);
            flanks.add(Flank.RIGHT);
        }

        return flanks;
    }
}

