
//#include <angelscript.h>
#include <scriptbuilder/scriptbuilder.h>
#include <assert.h>

#include "Log.h"
#include "scripting.h"
#include "settings.h"

bool g_fullscreen = false;
int g_screenWidth = 800;
int g_screenHeight = 600;
int g_cameraMode = CM_FOLLOW_PLAYER;
bool g_doDebugDraw = false;
float g_playerRunStrength = 7.5;
float g_playerRunSpeed = 12.5;
float g_playerJumpStrength = 4;
float g_playerAirSteerStrength = 1;

void setFullscreen(bool tf)
{
    g_fullscreen = tf;

    g_log.log(LL_INFO, "Setting fullscreen: %s", tf ? "true":"false");
}

void setDisplayDimensions(int width, int height)
{
    g_screenWidth = width;
    g_screenHeight = height;

    g_log.log(LL_INFO, "Setting display dimensions: %dx%d", width, height);
}

void setCameraMode(int mode)
{
    g_cameraMode = CM_FOLLOW_PLAYER;
    if ( mode == CM_PAN_WITH_MOUSE )
        g_cameraMode = CM_PAN_WITH_MOUSE;

    g_log.log(LL_INFO, "Setting camera mode: %s", mode == CM_PAN_WITH_MOUSE ? "pan with mouse":"follow player" );
}

void setDoDebugDraw(bool tf)
{
    g_doDebugDraw = tf;

    g_log.log(LL_INFO, "Setting debug draw: %s", tf ? "true":"false");
}

void setPlayerStats(float runStrength, float runSpeed, float jumpStrength, float airSteerStrength)
{
    g_playerRunStrength = runStrength;
    g_playerRunSpeed = runSpeed;
    g_playerJumpStrength = jumpStrength;
    g_playerAirSteerStrength = airSteerStrength;

    g_log.log(LL_INFO, "Setting player stats: %.3f, %.3f, %.3f, %.3f", runStrength, runSpeed, jumpStrength, airSteerStrength);
}

/////////////

void loadSettings()
{
    assert(g_scriptEngine);

    CScriptBuilder builder;
    int r = builder.StartNewModule(g_scriptEngine, "settings");
    if( r < 0 )
    {
        g_log.log(LL_ERROR, "StartNewModule failed (settings)");
        return;
    }

    //it's bad if this fails
    string scriptFile("settings.as");
    r = builder.AddSectionFromFile(scriptFile.c_str());
    if( r < 0 )
    {
        g_log.log(LL_ERROR, "AddSectionFromFile failed (%s), using default settings", scriptFile.c_str());
        return;
    }

    r = builder.BuildModule();
    if( r < 0 )
    {
        g_log.log(LL_ERROR, "BuildModule failed (%s), using default settings", scriptFile.c_str());
        return;
    }

    //now call the doSettings function
    asIScriptModule *mod = g_scriptEngine->GetModule("settings");
    asIScriptFunction *func = mod->GetFunctionByDecl("void doSettings()");
    if( func == 0 )
    {
        g_log.log(LL_ERROR, "No function \"void doSettings()\" in file %s, using default settings", scriptFile.c_str());
        return;
    }

    asIScriptContext *ctx = g_scriptEngine->CreateContext();
    ctx->Prepare(func);
    r = ctx->Execute();
    if( r != asEXECUTION_FINISHED )
    {
        if( r == asEXECUTION_EXCEPTION )
        {
            g_log.log(LL_ERROR, "Problem calling function \"void doSettings()\" in file %s", scriptFile.c_str());
            return;
        }
    }

    ctx->Release();

}




