import * as Sfs3 from "sfs3-api";

let sfs:Sfs3.SmartFox;

window.onload = () => {
    connect();
};

function trace(str: string): void
{
	console.log('%c' + str, 'color: #6FBFF9');
    
    let p = document.createElement("p");
    p.innerHTML = str;
    document.getElementById("out").append(p);
}

function connect()
{
    // Create instance
	sfs = new Sfs3.SmartFox();
	
    // Configure
	sfs.config.zone = "Playground";
	sfs.config.netDebugLevel = Sfs3.NetDebugLevel.PROTOCOL;
	sfs.logger.level = Sfs3.LogLevel.DEBUG;

	sfs.addEventListener(Sfs3.SFSEvent.CONNECTION, onConnection, this);
	sfs.addEventListener(Sfs3.SFSEvent.CONNECTION_LOST, onConnectionLost, this);
	sfs.addEventListener(Sfs3.SFSEvent.LOGIN, onLogin, this);
	sfs.addEventListener(Sfs3.SFSEvent.LOGIN_ERROR, onLoginError, this);
	sfs.addEventListener(Sfs3.SFSEvent.ROOM_JOIN, onRoomJoin, this);
	sfs.addEventListener(Sfs3.SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError, this);

    trace("API version: " + sfs.version);

	sfs.connect();
}

//----------------------------------------------------------------------------//

function onConnection(evt:Object)
{
    const success:Boolean = evt[Sfs3.EventParam.Success];

    if (success)
    {
        trace("Connection successful");

        // Login
        sfs.send(new Sfs3.LoginRequest()); 
    }
    else
        trace("Connection failed");
}

function onConnectionLost(evt:Object)
{
    trace("Connection lost; reason is " + evt[Sfs3.EventParam.DisconnectionReason]);
}

function onLogin(evt:Object)
{
    trace(`Logged in zone ${evt[Sfs3.EventParam.ZoneName]} as ${evt[Sfs3.EventParam.User]}`);

    // Join room
    sfs.send(new Sfs3.JoinRoomRequest("Lobby"));
}

function onLoginError(evt:Object)
{
    trace(`Login error: ${evt[Sfs3.EventParam.ErrorMessage]} (code: ${evt[Sfs3.EventParam.ErrorCode]})`);
}

function onRoomJoin(evt:Object)
{
    trace(`Room joined succesfully: ${evt[Sfs3.EventParam.Room]}`);
}

function onRoomJoinError(evt:Object)
{
    trace(`Room join error: ${evt[Sfs3.EventParam.ErrorMessage]} (code: ${evt[Sfs3.EventParam.ErrorCode]})`);
}