/*
 * This file is almost CG's toggle module from the SDK.  I'd have
 * subclassed it if it were an option.
 */

package com.codingame.game;

import java.util.HashMap;
import java.util.Map;

import com.codingame.gameengine.core.AbstractPlayer;
import com.codingame.gameengine.core.GameManager;
import com.codingame.gameengine.core.Module;
import com.codingame.gameengine.module.entities.Entity;
import com.codingame.gameengine.module.entities.GraphicEntityModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * @author Jean Porée, JBM
 * 
 *         This module allows you to display or hide elements of the GraphicEntityModule using the viewer's options menu.
 * 
 */
@Singleton
public class PantsModule implements Module {

    GameManager<AbstractPlayer> gameManager;
    @Inject GraphicEntityModule entityModule;
    Map<Integer, Object> registered, newRegistration;

    class Toggle {
        public String name;
        public boolean state = true;

        public Toggle(String name, boolean state) {
            this.name = name;
            this.state = state;
        }
    }

    class Pants {
        String name = "pants";
        int state = 1;
        Pants(int state) { this.state = state; }
    }

    @Inject
    PantsModule(GameManager<AbstractPlayer> gameManager) {
        this.gameManager = gameManager;
        gameManager.registerModule(this);
        registered = new HashMap<>();
        newRegistration = new HashMap<>();
    }

    @Override
    public void onGameInit() {
        sendFrameData();
    }

    @Override
    public void onAfterGameTurn() {
        sendFrameData();
    }

    @Override
    public void onAfterOnEnd() {}

    private void sendFrameData() {
        Object[] data = { newRegistration };
        gameManager.setViewData("toggles", data);

        newRegistration.clear();
    }
    /**
     * Will display the entity only when the toggle state matches the state you set
     * 
     * @param entity which will be displayed
     * @param toggle the name of the toggle you want to use
     * @param state the state of the toggle where the entity will be displayed at
     */
    public void displayOnToggleState(Entity<?> entity, String toggle, boolean state) {
        int id = entity.getId();
        Toggle associatedToggle = new Toggle(toggle, state);
        if (!associatedToggle.equals(registered.get(id))) {
            newRegistration.put(id, associatedToggle);
            registered.put(id, associatedToggle);
        }
    }

    public void displayOnPantsState(Entity<?> entity, int state) {
        int id = entity.getId();
        Pants associatedPants = new Pants(state);
        if (!associatedPants.equals(registered.get(id))) {
            newRegistration.put(id, associatedPants);
            registered.put(id, associatedPants);
        }
    }
}
