using System;
using Godot;

using Sfs3.Client;
using Sfs3.Client.Core;
using Sfs3.Client.Util;

public partial class GlobalManager : Node
{
    private SmartFox sfs;
    private string lastDisconnectionMsg = "";

    public override void _Ready()
    {
        Trace("Global Manager ready");
    }

    public override void _Process(double delta)
    {
        // Process the SmartFox events queue
        if (sfs != null)
            sfs.ProcessEvents();
    }

    public override void _Notification(int what)
    {
        if (what == NotificationWMCloseRequest)
        {
            if (sfs != null && sfs.IsConnected)
                sfs.Disconnect();

            Trace("Application quit");
        }
    }

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

    public void Trace(string str)
    {
        GD.PrintRich(String.Format("[color=#6FBFF9]{0}[color=white]", str));
    }

    public SmartFox CreateSfsClient()
    {
        sfs = new SmartFox();
        sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
        return sfs;
    }

    public SmartFox GetSfsClient()
    {
        return sfs;
    }

    public string LastDisconnectionMsg => lastDisconnectionMsg;

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

    private void OnConnectionLost(ApiEvent evt)
    {
        // Get disconnection reason
		string reason = (string)evt.Params[EventParam.DisconnectionReason];

		Trace("Connection to SmartFoxServer lost; reason is: " + reason);

        // Show disconnection reason
        if (reason != ClientDisconnectionReason.MANUAL)
        {
            // Save disconnection message, which can be retrieved by the LOGIN scene to display an error message
            lastDisconnectionMsg = "An unexpected disconnection occurred.\n";

            if (reason == ClientDisconnectionReason.IDLE)
                lastDisconnectionMsg += "It looks like you have been idle for too much time.";
            else if (reason == ClientDisconnectionReason.KICKED)
                lastDisconnectionMsg += "You have been kicked by an administrator or moderator.";
            else if (reason == ClientDisconnectionReason.BANNED)
                lastDisconnectionMsg += "You have been banned by an administrator or moderator.";
            else
                lastDisconnectionMsg += "The reason of the disconnection is unknown.";
        }
        else
            lastDisconnectionMsg = "";

        // Switch to login scene
        if (!GetTree().CurrentScene.SceneFilePath.EndsWith("Login.tscn"))
            GetTree().ChangeSceneToFile("scenes/Login.tscn");
    }
}
