package electrosphere.game.server.structure.virtual;

import com.google.gson.Gson;

import electrosphere.engine.Globals;
import electrosphere.server.db.DatabaseResult;
import electrosphere.server.db.DatabaseResultRow;

import java.util.LinkedList;
import java.util.List;

/**
 * Manages all server views of structures
 */
public class StructureManager {
    
    static Gson serializer;
    
    static {
        serializer = new Gson();
    }
    
    static int structIDIterator = 0;
    
    
    public static Structure createStructure(int worldX, int worldY, float localX, float localY, String type){
        structIDIterator++;
        Structure rVal = new Structure(worldX, worldY, localX, localY, type);
        Globals.dbController.executePreparedStatement("INSERT INTO structWorldPositions (structID,posX,posY) VALUES (?,?,?);",structIDIterator,worldX,worldY);
        Globals.dbController.executePreparedStatement("INSERT INTO structData(structID,propName,propValue) VALUES(?,'localX','?');",structIDIterator,localX);
        Globals.dbController.executePreparedStatement("INSERT INTO structData(structID,propName,propValue) VALUES(?,'localY','?');",structIDIterator,localY);
        return rVal;
    }
    
    public static List<Structure> getStructuresInChunk(int worldX, int worldY){
        List<Structure> rVal = new LinkedList<Structure>();
        DatabaseResult result = Globals.dbController.executePreparedQuery("SELECT * FROM structWorldPositions WHERE posX = ? AND posY = ?;",worldX,worldY);
        List<Integer> returnedIDs = new LinkedList<Integer>();
        if(result.success() && result.hasResult()){
            for(DatabaseResultRow row : result){
                returnedIDs.add(row.getAsInteger("structID"));
            }
        }
        if(returnedIDs.size() > 0){
            String ids = "";
            for(int ID : returnedIDs){
                ids = ids + ID + ",";
            }
            ids = ids.substring(0, ids.length() - 1);
            result = Globals.dbController.executePreparedQuery("SELECT * FROM structData WHERE structID IN (?);",ids);
            if(result.success() && result.hasResult()){
                for(DatabaseResultRow row : result){
                    Structure newStruct = serializer.fromJson(row.getAsString("dataVal"), Structure.class);
                    rVal.add(newStruct);
                }
            }
        }
        return rVal;
    }
}
