package cicaprojekt;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

public class Stargate {
    public static final Stargate yellowStargate = new Stargate("Yellow Stargate");
    public static final Stargate blueStargate = new Stargate("Blue Stargate");
    public static final Stargate redStargate = new Stargate("Red Stargate");
    public static final Stargate greenStargate = new Stargate("Green Stargate");
    public Stargate other;
    private boolean isSpawned;
    private Wall currentWall;
    private Direction exitDirection;
    private String name;

    private static Map<Color, Stargate> stargates = new HashMap<>();


    private Stargate(String name) {
        isSpawned = false;
        this.name = name;
    }

    public static void init() {
        yellowStargate.other = blueStargate;
        blueStargate.other = yellowStargate;
        redStargate.other = greenStargate;
        greenStargate.other = redStargate;

        stargates.put(Color.YELLOW, yellowStargate);
        stargates.put(Color.BLUE, blueStargate);
        stargates.put(Color.RED, redStargate);
        stargates.put(Color.GREEN, greenStargate);
    }

    public static Stargate get(Color color) {
        return stargates.get(color);
    }

    public Wall getCurrentWall() {
        return currentWall;
    }

    public void setCurrentWall(Wall wall, Direction direction) {
        currentWall = wall;
        if(direction != null)
            exitDirection = Direction.invert(direction);
        if(wall != null) {
            isSpawned = true;
        }
        else {
            isSpawned = false;
        }
    }

    public boolean isSpawned() {
        return isSpawned;
    }

    public boolean isOpen() {
        if(isSpawned & other.isSpawned)
            return other.getCurrentWall().getAdjacentTile(other.getExitDirection()).isSteppable();
        return false;
    }

    private Direction getExitDirection() {
        return exitDirection;
    }

    public void teleport(PlayerBase player) {
        if(isOpen())
        {
            Tile exit = other.getCurrentWall().getAdjacentTile(other.getExitDirection());
            player.setCurrentTile(exit);
            exit.onEntry(player);
        }
        else
            player.setCurrentTile(this.getCurrentWall());
    }

    @Override
    public String toString() {
        if(isSpawned)
            return String.format("%s: %s", name, currentWall);
        else return String.format("%s: not spawned", name, currentWall);
    }
    
    public String getName() {
        return name;
    }
}
