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

public class NetworkServerUI : MonoBehaviour {

    public Move []  playerS;
    int index = 0;
    public Dictionary<string, Move> mappingPlayer;
    public GameManager manager;

    private bool init = false;

    void Start ()
    {

        mappingPlayer = new Dictionary<string, Move>();
        UnityEngine.Networking.NetworkServer.Listen(25000);
        UnityEngine.Networking.NetworkServer.RegisterHandler(888, ServerReceiveMessage);

    }


    public bool isStartGame(int number)
    {
        return mappingPlayer.Count >= number;
    }



	
    private void ServerReceiveMessage(NetworkMessage message)
    {
        StringMessage msg = new StringMessage();
        msg.value = message.ReadMessage<StringMessage>().value;

        Debug.Log(msg.value);

        if(msg.value.Contains("|"))
        {
            string[] deltas = msg.value.Split('|');
            if(mappingPlayer.ContainsKey(deltas[0]))
                 mappingPlayer[deltas[0]].MovePlayer(Convert.ToSingle(deltas[1]), Convert.ToSingle(deltas[2]));

            else
            {

                if (!init)
                {
                    mappingPlayer.Add(deltas[0], playerS[index]);
                    index++;
                    if (index == manager.PlayersCount)
                    {
                        manager.Init();
                        init = true;
                    }
                }
            }
        }

        

    }
	// Update is called once per frame
	void OnGUI () {

        string ipAddress = Network.player.ipAddress;
        GUI.Box(new Rect(10, Screen.height - 50, 100, 50), ipAddress);
        GUI.Label(new Rect(20 ,Screen.height - 35, 100, 20), "STATUS:" + NetworkServer.active);
	}
}
