using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Collections.Generic;

using SmartFoxClientAPI;
using SmartFoxClientAPI.Data;


namespace SmartFoxChat
{
	public partial class MainPage : UserControl
	{
		private const String STATE_CONNECTION = "Connection";
		private const String STATE_LOGIN = "Login";
		private const String STATE_CHAT = "Chat";
		private const String STATE_DISCONNECTION = "Disconnection";
		
		private SmartFoxClient sfs;
		private bool isFirstJoin = true;
		
		public MainPage()
		{
			// Required to initialize variables
			InitializeComponent();
			
			VisualStateManager.GoToState(this, STATE_CONNECTION, true);
			sfs = new SmartFoxClient(true);
			
			SFSEvent.onConnection += OnConnection;
			SFSEvent.onConnectionLost += OnConnectionLost;
			SFSEvent.onRoomListUpdate += OnRoomListUpdate;
			SFSEvent.onLogin += OnLogin;
			SFSEvent.onJoinRoom += OnJoinRoom;
			SFSEvent.onJoinRoomError += OnJoinRoomError;
			SFSEvent.onUserCountChange += OnUserCountChange;
			SFSEvent.onPublicMessage += OnPublicMessage;
		}
		
		//-------------------------------------------------------------------------------------------------
		// SmartFoxServer Event Handlers
		//-------------------------------------------------------------------------------------------------
		
		private void OnConnection(bool success, string error) 
		{
  			if (success)
			{
				VisualStateManager.GoToState(this, STATE_LOGIN, true);
			}
			else
			{
				TB_ConnectionErr.Text = error;
				BT_Connect.IsEnabled = true;
			}
        }
		
		private void OnConnectionLost() 
		{
			VisualStateManager.GoToState(this, STATE_DISCONNECTION, true);
			BT_Connect.IsEnabled = true;
			BT_Login.IsEnabled = true;
        }
		
        private void OnLogin(bool success, string name, string error)
        {
            if (success)
			{
				VisualStateManager.GoToState(this, STATE_CHAT, true);
				TB_Nickname.Text = "Logged as: " + name;
			}
			else
			{
				TB_LoginError.Text = error;
				BT_Connect.IsEnabled = true;
			}
        }
		
		private void OnRoomListUpdate(Dictionary<int, Room> roomList)
		{
			populateRoomList();
			sfs.AutoJoin();
		}
		
		private void OnJoinRoom(Room room)
		{
			TB_ChatHistory.Text = "";
			addToChatHistory("{ Joined: " + room.GetName() + " }");
			populateUserList(room);
			
			/*
			if (isFirstJoin)
			{
				foreach (object item in LB_RoomList.Items)
				{
					RoomListItem rItem = (RoomListItem) item;
					if (rItem.Id == room.GetId())
					{
						LB_RoomList.SelectedIndex = 0;
						break;
					}
				}
			}
			*/
		}
		
		private void OnJoinRoomError(string error)
		{
			addToChatHistory("{ Last Join attempt failed: " + error + " }");
		}
		
		private void OnUserCountChange(Room room)
		{
			populateRoomList();
		}
		
		private void OnPublicMessage(string message, User sender, int roomId)
		{
			addToChatHistory(sender.GetName() + ": " + message);
		}
		
		//-------------------------------------------------------------------------------------------------
		// Helper Methods
		//-------------------------------------------------------------------------------------------------
		private void populateRoomList()
		{
			LB_RoomList.Items.Clear();
			
			foreach (Room room in sfs.GetAllRooms().Values)
			{
				string itemLabel = room.GetName() + " (" + room.GetUserCount() + "/" + room.GetMaxUsers() + ")";
				RoomListItem rlItem = new RoomListItem(itemLabel, room.GetId());
				LB_RoomList.Items.Add(rlItem);
			}
		}
		
		private void populateUserList(Room theRoom)
		{
			LB_UserList.Items.Clear();
			
			foreach (User user in theRoom.GetUserList().Values)
			{
				LB_UserList.Items.Add(user.GetName());
			}
		}
		
		private void addToChatHistory(string message)
		{
			TB_ChatHistory.Text += message + "\n";
			TB_ChatHistory.SelectionStart = TB_ChatHistory.Text.Length;
		}
		
		//-------------------------------------------------------------------------------------------------
		// GUI Event Handlers
		//-------------------------------------------------------------------------------------------------
		
		private void OnBTConnect_Click(object sender, System.Windows.RoutedEventArgs e)
		{	
			Button target = (Button) sender;
			target.IsEnabled = false;
			
			// Start connection with SmartFoxServer
			sfs.SetQueuePollSpeed(250);
			sfs.Connect(TB_IpAddress.Text, int.Parse(TB_Port.Text));
		}

		private void OnBTLogin_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			Button target = (Button) sender;
			target.IsEnabled = false;
			
			sfs.Login("simpleChat", TB_UserName.Text, "");
		}

		private void OnBTLogOut_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			sfs.Disconnect();
		}

		private void OnBTSendMessage_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			if (TB_ChatMessage.Text.Length > 0)
			{
				sfs.SendPublicMessage(TB_ChatMessage.Text);
				TB_ChatMessage.Text = "";
			}
			
		}

		private void OnBTGoBack_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			VisualStateManager.GoToState(this, STATE_CONNECTION, true);
		}

		private void OnLBRoomList_Change(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			/*
			if (isFirstJoin)
			{
				addToChatHistory("FIRST JOIN DETECTED!");
				isFirstJoin = false;
				return;
			}
			*/
			
			ListBox list = (ListBox) sender;
			RoomListItem item = (RoomListItem) list.SelectedItem;
			sfs.JoinRoom(item.Id, "", false, false, -1);
		}
	}
}