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

namespace Networking.Client
{

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

#if UNITY_EDITOR

        [SerializeField]
        [Multiline]
        private string DevNotes;

#endif

        /// <summary>
        /// All Clients which are Currently Connected;
        /// </summary>
        [SerializeField]
        public List<ClientData> AllClients;

        /// <summary>
        /// Called when a client connects or disconnet 
        /// </summary>
        public System.Action<List<ClientData>> OnClientsChange;

        public void SetUp(ClientObject client)
        {
            Reset();
            client.client.RegisterHandler(LoginProtocols.OtherClientConnected, OnClientConnect);
            client.client.RegisterHandler(LoginProtocols.OtherClientDisconnected, OnClientDisconnect);
        }

        
        public void Reset()
        {
            AllClients = new List<ClientData>();

            OnClientsChange?.Invoke(AllClients);
        }


        public void OnClientConnect(NetworkMessage msg)
        {
            LoginProtocols.LoginMsg loginMsg;
            if (!msg.TryRead(out loginMsg))
                return;


            AllClients.Add(new ClientData(loginMsg));
            OnClientsChange?.Invoke(AllClients);
        }

        public void OnClientDisconnect(NetworkMessage msg)
        {
            LoginProtocols.LoginMsg loginMsg;
            if (!msg.TryRead(out loginMsg))
                return;

            AllClients.RemoveAll(p => (p.Name == loginMsg.Name) && (p.Color == loginMsg.Color) && (p.characterAnimal == loginMsg.Animal));
            OnClientsChange?.Invoke(AllClients);
        }


    }


    [System.Serializable]
    public class ClientData
    {

        /// <summary>
        /// Client Name
        /// </summary>
        public string Name;

        /// <summary>
        /// Color which represents player, picked by player
        /// </summary>
        public Color Color;

        /// <summary>
        /// Clients character animal - needed for instantiation
        /// </summary>
        public string characterAnimal = "Bear";

        public ClientData(LoginProtocols.LoginMsg msg)
        {
            this.Name = msg.Name;
            this.Color = msg.Color;
            this.characterAnimal = msg.Animal;
        }
    }

}
