package electrosphere.server.db;

import electrosphere.engine.Globals;
import electrosphere.logger.LoggerInterface;
import electrosphere.util.FileUtils;
import java.io.IOException;

/**
 *
 * @author satellite
 */
public class DatabaseUtils {

    
    public static boolean initCentralDBFile(String path){
        String sanitizedPath = FileUtils.sanitizeFilePath(path);
        if(!FileUtils.checkFileExists(sanitizedPath)){
            return false;
        }
        String dbFilePath = sanitizedPath + "/central.db";
        if(Globals.dbController == null){
            Globals.dbController = new DatabaseController();
        }
        if(!Globals.dbController.isConnected()){
            Globals.dbController.connect(dbFilePath);
        }
        runScript(Globals.dbController,"createTables.sql");
        //both of these are used for arena mode as well as main game
        runScript(Globals.dbController,"/auth/createAuthTables.sql");
        runScript(Globals.dbController,"/character/createCharacterTables.sql");
        //create adventure-only files
        if(!dbFilePath.equals("./saves/arena/central.db")){
            //we only want to create these if we're not in arena mode
            runScript(Globals.dbController,"/towns/createTownsTables.sql");
            runScript(Globals.dbController,"/structs/createStructsTables.sql");
        }
        Globals.dbController.disconnect();
        return true;
    }

    public static boolean runScript(DatabaseController controller, String scriptPath){
        String rawScript = "";
        try {
            rawScript = FileUtils.getSQLScriptFileAsString(scriptPath);
        } catch (IOException ex) {
            LoggerInterface.loggerEngine.ERROR("Failure reading create db script", ex);
            return false;
        }
        String[] scriptLines = rawScript.split("\n");
        String accumulatorString = "";
        for(String line : scriptLines){
            if(line.length() > 1 && !line.startsWith("--")){
                if(line.contains(";")){
                    accumulatorString = accumulatorString + line;
                    LoggerInterface.loggerDB.INFO("EXECUTE: " + accumulatorString);
                    controller.executePreparedStatement(accumulatorString);
                    accumulatorString = "";
                } else {
                    accumulatorString = accumulatorString + line;
                }
            }
        }
        return true;
    }


}
