using UnityEngine;
using System.Collections;

public class chatScript : MonoBehaviour 
{
    public GUISkin myskin;
	
	
    private Rect windowRect = new Rect(585, 120, 300, 450);
    private string messBox = "", messageToSend = "", user = "";
	bool usertwo = false;
	private string userlog = "";

    private void OnGUI()
    {
        GUI.skin = myskin;
        if (NetworkPeerType.Disconnected != Network.peerType)
            windowRect = GUI.Window(1, windowRect, windowFunc, "Chat");
    }

   
	private void windowFunc(int id)
    {
		
        GUILayout.Box(messBox, GUILayout.Height(350));
		
        GUILayout.BeginHorizontal();
        messageToSend = GUILayout.TextField(messageToSend);
		// on click send send mesage through rpc to all connected
        if (GUILayout.Button("Send" , GUILayout.Width(75)))
        {
			// check if message is empty
			if (messageToSend != "")
			{ 
				//if username is true send saved username instead of username field
				if(usertwo == true)
				{
		    networkView.RPC("SendMessage", RPCMode.All, userlog + ": " + messageToSend + "\n");
            messageToSend = "";
				}
				//name check 
				if(usertwo == false)
				{
					//send mesage save username and set username check to true
         		    networkView.RPC("SendMessage", RPCMode.All, user + ": " + messageToSend + "\n");
          		    messageToSend = "";
					userlog = userlog + user;
					usertwo = true;
				}
			
			}
        }
		// on enter send message through rpc to all connected 
		if (Input.GetKey (KeyCode.Return))
		{
			if (messageToSend != "")
			{	
			if(usertwo == true)
				{
		    networkView.RPC("SendMessage", RPCMode.All, userlog + ": " + messageToSend + "\n");
            messageToSend = "";
				}
			if(usertwo == false)
				{
			networkView.RPC("SendMessage", RPCMode.All, user + ": " + messageToSend + "\n");
            messageToSend = "";
			userlog = userlog + user;
			usertwo = true;
				}
				
			}
		}
			
			
			
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Label("User:");
        user = GUILayout.TextField(user);

        GUILayout.EndHorizontal();
		//make window dragable
        GUI.DragWindow(new Rect(0, 0, Screen.width, Screen.height));
    }
	//broadcast message to all connected chatboxes
    [RPC]
     internal void SendMessage(string mess)
    {
        messBox += mess;
    }
}
