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

public class NetworkCommandRunner : NetworkBehaviour
{
    public static NetworkCommandRunner CurrentCommandRunner;
	public NetworkConnection myNetworkConnection;
	public NetworkIdentity myNetId;
	public static int RandomGameSeed = 0;
	Commands commands { get { return Game.CurrentGame.GameCommands; } }
	public bool isServer { get { return NetworkServer.connections.Count > 0; } } 

	public void AddCommand(CommandInput input)
	{
		CmdAddCommandToServer(input);
		Debug.Log ("Send " + input.input + " to server. " + myNetworkConnection.isReady);
	}

	[Command]
	void CmdAddCommandToServer(CommandInput input)
	{
		Debug.Log ("Adding command from client: " + input.input);
		Game.CurrentGame.AddInput(input);
	}

    void OnEnable()
    {
        CurrentCommandRunner = this;
		myNetId = GetComponent<NetworkIdentity> ();
    }

    public void RunNetworkCommand(Command command)
    {
        RpcRunNetworkCommand(command);
    }

    [ClientRpc]
    private void RpcRunNetworkCommand(Command command)
    {
        commands.RunCommand(command);
    }


	[ClientRpc]
	void RpcStartGame()
	{
		// RUN ON ALL CLIENTS
		Game.CurrentGame.CreateGame ();
		RandomGameSeed = Mathf.RoundToInt(Random.Range(0,10));
        Debug.Log(RandomGameSeed);
	}

	public void StartGame()
	{
		// RUN ON SERVER ONLY
		Game.CurrentGame.InitCommandRunner();
		RpcStartGame ();
	}

	public void AddPoint(int playerId)
	{
		if(isServer)
			RpcAddPoint(playerId);
	}

	[ClientRpc]
	void RpcAddPoint(int playerId)
	{
		Game.CurrentGame.Players[playerId].AddPoint();
	}

    [ClientRpc]
    void RpcNormalSpeedClient()
    {
        if(!isServer)
        {
            Game.CurrentGame.StartCoroutine(Game.CurrentGame.NormalTime());
        }
    }

    [ClientRpc]
    void RpcSlowMoClient()
    {
        if(!isServer)
        {
            Game.CurrentGame.StartCoroutine(Game.CurrentGame.SlowMoTime());
        }
    }

    public void NormalSpeedClient()
    {
        RpcNormalSpeedClient();
    }

    public void SlowMoClient()
    {
        RpcSlowMoClient();
    }
}
