// ----
//
// This file contains links to the initialisation functions, and the
// preference loading/saving functions.  It also initially loads and saves
// the preferences when starting and exiting.
//
// ----

$game::settings::prefs       = expandFilename( "./prefs/prefs.cs" );
$game::settings::keyConfig   = expandFilename( "./prefs/keyConfig.cs" );

// -----------------------------------------------------------------------------
// Load up defaults console values.
// ----

function savePrefs()
{
    echo("exporting prefs...");
    export("$pref::*", $game::settings::prefs, false);

    if(isFile($game::settings::prefs))
        exec( $game::settings::prefs );
}

function loadPrefs()
{
    exec( "./scripts/client/default.pref.cs" );
    exec( "./scripts/server/default.pref.cs" );

    if(isFile($game::settings::prefs))
        exec( $game::settings::prefs );
}

function loadKeyConfig()
{
    // -- Default player key bindings
    exec("./scripts/client/default.bind.cs");
    if(isFile($game::settings::keyConfig))
        exec( $game::settings::keyConfig );
}

function saveKeyConfig()
{
    if(isObject(moveMap))
        moveMap.save($game::settings::keyConfig);
    if(isObject(observerMap))
        observerMap.save($game::settings::keyConfig, true);
    if(isObject(wheeledVehicleMap))
        wheeledVehicleMap.save($game::settings::keyConfig, true);
    if(isObject(flyingVehicleMap))
        flyingVehicleMap.save($game::settings::keyConfig, true);
    if(isObject(hoverVehicleMap))
        hoverVehicleMap.save($game::settings::keyConfig, true);
}

function restoreClientDefaults()
{
    MB_yesno( "Confirmation...", "Are you sure you want to restore client defaults?", "dorestoreClientDefaults();" );
}

function dorestoreClientDefaults()
{
    exec( "./scripts/client/default.pref.cs" );
    savePrefs();
    canvas.popDialog(ui_optionsGui);
    canvas.pushDialog(ui_optionsGui);
    ui_optionsGui.onAccept();
    canvas.pushDialog(ui_optionsGui);
}

function restoreServerDefaults()
{
    MB_yesno( "Confirmation...", "Are you sure you want to restore server defaults?", "dorestoreServerDefaults();" );
}

function dorestoreServerDefaults()
{
    exec( "./scripts/server/default.pref.cs" );
    savePrefs();
    Canvas.popDialog(ui_hostOptionsGui);
    Canvas.pushDialog(ui_hostOptionsGui);
}
// -----------------------------------------------------------------------------
// Package overrides to initialize the mod
// ----

package legends {

function displayHelp()
{
    Parent::displayHelp();
    error(
             "Legends command line options:"
    @ "\n" @ "  -prefs <configFile>    Exec the config file"
    @ "\n" @ "  -dedicated             Start as dedicated server"
    @ "\n" @ "  -mission <filename>    For dedicated: Load mission <filename>"
    @ "\n" @ "  -connect <address>     For non-dedicated: Connect to a game at <address>"
    @ "\n" @ "  -password <password>   When connect is used: specify target server password"
    @ "\n" @ "  -port <port_number>    Uses the port number specified"
    @ "\n"
    );
}

function parseArgs()
{
    // -- load the key-binds
    loadKeyConfig();
    // -- init your preferences
    loadPrefs();

    // -- Call the parent
    Parent::parseArgs();

    // -- Arguments, which override everything else.
    for( %i = 1; %i < $Game::argc; %i++ )
    {
        %arg = $Game::argv[%i];
        %nextArg = $Game::argv[%i+1];
        %hasNextArg = $Game::argc - %i > 1;

        switch$( %arg )
        {
            // ---- ---- ---- ----
            case "-prefs":
                $argUsed[%i]++;
                if( %hasNextArg )
                {
                    exec(%nextArg, true, true);
                    $argUsed[%i+1]++;
                    %i++;
                }
                else
                    error("Error: Missing Command Line argument. Usage: -prefs <path/script.cs>");

            // ---- ---- ---- ----
            case "-dedicated":
                enableWinConsole(true);
                $Server::Dedicated = true;
                $argUsed[%i]++;

            // ---- ---- ---- ----
            case "-mission":
                $argUsed[%i]++;
                if( %hasNextArg )
                {
                    $missionArg = %nextArg;
                    $argUsed[%i+1]++;
                    %i++;
                }
                else
                    error("Error: Missing Command Line argument. Usage: -mission <filename>");

            // ---- ---- ---- ----
            case "-gametype":
                $argUsed[%i]++;
                if( %hasNextArg )
                {
                    $missionType = %nextArg;
                    $argUsed[%i+1]++;
                    %i++;
                }
                else
                    error("Error: Missing Command Line argument. Usage: -gametype <gametype>");

            // ---- ---- ---- ----
            case "-connect":
                $argUsed[%i]++;
                if( %hasNextArg )
                {
                    $JoinGameAddress = %nextArg;
                    $argUsed[%i+1]++;
                    %i++;
                }
                else
                    error("Error: Missing Command Line argument. Usage: -connect <ip_address>");

            // ---- ---- ---- ----
            case "-password":
                $argUsed[%i]++;
                if( %hasNextArg )
                {
                    $JoinGamePassword = %nextArg;
                    $argUsed[%i+1]++;
                    %i++;
                }
                else
                    error("Error: Missing Command Line argument. Usage: -password <password>");

            // ---- ---- ---- ----
            case "-port":
                $argUsed[%i]++;
                if( %hasNextArg )
                {
                    $missionPortArg = %nextArg;
                    $argUsed[%i+1]++;
                    %i++;
                }
                else
                    error("Error: Missing Command Line argument. Usage: -port <port_number>");
        }
    }
}

function onStart()
{
    Parent::onStart();
    warn("\n--------- Initializing MOD: Legends ---------");

    // -- Load the scripts that start it all...
    exec("./scripts/init.cs");
//    exec("./data/init.cs");

    if(isFile("./prefs/banlist.cs"))
        exec("./prefs/banlist.cs");
    if(isFile("./prefs/mapcycle.cs"))
        exec("./prefs/mapcycle.cs");
    // -- Server is loaded for all sessions as clients can host in-game servers
    initServer();

    // -- Start up in either client, or dedicated server mode
    if( $Server::Dedicated || isDedicated() )
        initDedicated();
    else
    {
        initClient();
        // if a client specifies a mission fire it up immediately
        if ($missionArg !$= "")
        {
            createServer($missionArg, $missionType, $missionPortArg);
            connectlocal($pref::Server::Password);
        }
    }
}

function onExit()
{
    savePrefs();
    saveKeyConfig();
    export("$banlist::banPlayer*", "./prefs/banlist.cs", false);

    // ----

    if(isFunction(disconnectMe))
        disconnectMe();
    if(isObject(CDNCurler))
        CDNCurler.cancelDownloadTasks();

    Parent::onExit();
}

}; // -- Client package
activatePackage(legends);
