import * as Sfs3 from "sfs3-api";

// As an alternative, import specific classes:
//import { SmartFox, SFSEvent, ... } from "sfs3-api";

let sfs;

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

function trace(str)
{
	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)
{
    const success = evt[Sfs3.EventParam.Success];

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

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

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

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

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

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

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

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