package org.studiorailgun.sim.config.space;

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

import org.studiorailgun.FileUtils;

/**
 * Manages the region definitions
 */
public class RegionDefinitionManager {

    /**
     * Path to the root file
     */
    static final String ROOT_FILE_PATH = "./data/sim/region/world.json";
    
    /**
     * The definitions
     */
    Map<String,RegionDefinitionFile> definitions = new HashMap<String,RegionDefinitionFile>();

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

        RegionDefinitionManager.recursivelyParse(rVal, ROOT_FILE_PATH);

        return rVal;
    }

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

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

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