using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace Networking.Server {

    [CreateAssetMenu(menuName = "Major Project/Networking/ServerObject", order = 150)]
    public class ServerObject : ScriptableObject
    {

        #region Inspector Fields

        [Header("Server Settings")]
        [SerializeField]
        private int Port;

        [SerializeField]
        private bool useWebSockets;

        [SerializeField]
        private int webPort;

        [Header("References")]
        [SerializeField]
        private ClientList LoginHandler;

        

        #endregion Inspector Fields


        #region ReadOnly Variables
        public NetworkServerSimple server { get; private set;}
        private NetworkServerSimple webServer;

        #endregion ReadOnly Variables


        public void StartServer()
        {
            LoginHandler.ConnectedClients = new List<ClientData>();
            LoginHandler.DisconnectedClients = new List<ClientData>();
            //Debug.Log("Starting Server on " + port);
            server = new NetworkServerSimple();
            server.Configure(TransportConfigure.CreateConfigure(),32);

            if (useWebSockets)
            {
                webServer = new NetworkServerSimple();
                webServer.useWebSockets = true;
                webServer.Configure(TransportConfigure.CreateConfigure(), 32);
            }

            LoginHandler.SetUp(this);
            server.Listen(Port);
            webServer.Listen(webPort);
        }

        public void ServerClose()
        {
            if (server != null)
                server.Stop();

            if (webServer != null)
                webServer.Stop();
        }

        public void ServerUpdate()
        {
            if (server != null)
                server.Update();

            if (webServer != null)
                webServer.Update();
        }

        public void RegisterHandler(short msgType,NetworkMessageDelegate handler)
        {
            if (server != null)
            server.RegisterHandler(msgType, handler);

            if (webServer != null)
                webServer.RegisterHandler(msgType, handler);

        }

        public void UnregisterHandler(short msgType)
        {
            if (server != null)
                server.UnregisterHandler(msgType);

            if (webServer != null)
                webServer.UnregisterHandler(msgType);
        }

        public void DisconnectAllConnections()
        {
            if (server != null)
                server.DisconnectAllConnections();

            if (webServer != null)
                webServer.DisconnectAllConnections();
        }
    }
}
