package org.studiorailgun.sim.config.space;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.studiorailgun.FileUtils;

/**
 * Manages the location definitions
 */
public class LocationDefinitionManager {
    
    /**
     * Path to the root file
     */
    static final String ROOT_FILE_PATH = "./data/sim/location/loc.json";
    
    /**
     * The definitions
     */
    Map<String,LocationDefinition> definitions = new HashMap<String,LocationDefinition>();

    /**
     * Loads the location def manager
     * @return The location def manager
     */
    public static LocationDefinitionManager loadManager(){
        LocationDefinitionManager rVal = new LocationDefinitionManager();

        LocationDefinitionManager.recursivelyParse(rVal, ROOT_FILE_PATH);

        return rVal;
    }

    /**
     * Recursively parses for location definition files
     * @param manager The manager
     * @param path The current root path
     */
    private static void recursivelyParse(LocationDefinitionManager manager, String path){
        LocationDefinitionFile defFile = FileUtils.loadObjectFromFile(new File(path), LocationDefinitionFile.class);
        if(defFile.getLocations() != null){
            for(LocationDefinition def : defFile.getLocations()){
                manager.addDefinition(def);
            }
        }
        if(defFile.getDependencies() != null){
            for(String depPath : defFile.getDependencies()){
                recursivelyParse(manager, depPath);
            }
        }
    }

    /**
     * Adds a location definition to the manager
     * @param file
     */
    public void addDefinition(LocationDefinition file){
        definitions.put(file.getName(), file);
    }

    /**
     * Gets the location file by its name
     * @param name The name of the location
     * @return The definition if it exists, null otherwise
     */
    public LocationDefinition getDefinition(String name){
        return definitions.get(name);
    }

}
