using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ParticleFramework.Communication;
using ParticleFramework.Storage;
using ParticleFramework;
using Mobiles.Rooms;
using MySql.Data.MySqlClient;

namespace Mobiles.Users
{
    static class Handler
    {

        public static List<UserObject> clientObjects = new List<UserObject>();
        public static int botCount = 0;
        
        public static void login(string username, string password, TcpClient client, bool sendUserObject)
        {
            if (username == "" || username.ToLower() == "maarit")
            {
                client.Disconnect();
                return;
            }
            Log.Info("Client " + client.index + " logging in with username: " + username);

            if (DBManager.database.getString("SELECT COUNT(*) FROM `users` WHERE `name` = '" + username + "' AND `password` = '" + password + "'") != "0")
            {
                DBManager.database.closeClient();

                DBManager.database.noCommand("UPDATE `users` SET `lastvisit` = '" + String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "'` WHERE `name` = '" + username + "';");

                //build the user object
                UserObject userObject = newObject(username, password, client);

                foreach (UserObject user in clientObjects)
                {
                    if (user.username == userObject.username && userObject.tcpClient != client)
                    {
                        user.tcpClient.Disconnect();
                    }
                }

                if (clientObjects.Count <= (client.index + botCount) || clientObjects[client.index] == null)
                    {
                        client.userObject = userObject;
                        clientObjects.Add(userObject);
                    }
                    else
                    {
                        client.userObject = userObject;
                        clientObjects[client.index] = userObject;
                    }

                    if (!sendUserObject)
                    {
                        //Goto room 1 aka main!
                        RoomManager.toRoom(1, client);
                    }
                    else
                    {
                        client.sendData("USEROBJECT" + (char)13 + client.userObject.ToPrivate());
                    }

                DBManager.database.closeClient();
            }
            else
            {
                DBManager.database.closeClient();
                client.sendData("ERROR login in");
            }
        }

        public static void toAll(string Data)
        {
            foreach (UserObject user in clientObjects)
            {
                user.tcpClient.sendData(Data);
            }
        }

        public static void toAll(string Data, Boolean disconnect)
        {
            foreach (UserObject user in clientObjects)
            {
                user.tcpClient.sendData(Data);
                if(disconnect) user.tcpClient.Disconnect();
            }
        }

        public static void toUser(string Data, string uname)
        {
            foreach (UserObject user in clientObjects)
            {
                if (user.username.ToLower() == uname.ToLower())
                {
                    user.tcpClient.sendData(Data);
                }
            }
        }

        public static void toUser(string Data, string uname, Boolean disconnect)
        {
            foreach (UserObject user in clientObjects)
            {
                if (user.username.ToLower() == uname.ToLower())
                {
                    user.tcpClient.sendData(Data);
                    if (disconnect)
                    {
                        user.tcpClient.Disconnect();
                    }
                }
            }
        }

        public static void registerUser(string packet, TcpClient tclient)
        {
            packet = Security.Cleaner.cleanString(packet);
            string[] words = packet.Split(' ');
            string name = words[1], password = words[2], email = words[3];
            string pants, shirt, head;
            if (words[4].Contains("/"))
            {
                pants = words[4].Split('/')[0];
                shirt = words[4].Split('/')[1];
                head = words[4].Split('/')[2];
            }
            else
            {
                pants = words[4].Split(',')[0];
                shirt = words[4].Split(',')[1];
                head = words[4].Split(',')[2];
            }
            string sex = (words[7].ToString().Equals("Male") ? "M" : "F");
            string age = words[9].ToString();

            string mission = words[10].ToString();

            for (int i = 11; i < words.Length; i++)
            {
                if (i > 10) mission += " " + words[i];
            }

            //Stop invisibility
            if (pants == "" || pants == "0" || pants == "9") pants = "1";
            if (shirt == "" || shirt == "0" || shirt == "9") shirt = "1";
            if (head == "" || head == "0" || head == "9") head = "1";

            if (DBManager.database.getString("SELECT COUNT(*) FROM `users` WHERE `name` = '" + name + "' OR `email` = '" + email + "'") != "0")
            {
                tclient.sendData("ERROR That username or email is already registered!");
                return;
            }
            else
            {
                DBManager.database.noCommand("INSERT INTO `users` (`name`, `password`, `email`, `age`, `pants`, `shirt`, `head`, `sex`, `mission`, `created`, `rank`) VALUES ('" + name + "', '" + password + "', '" + email + "', '" + age + "', '" + pants + "', '" + shirt + "', '" + head + "', '" + sex + "', '" + mission + "', '" + String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "', '1');");
                Handler.login(name, password, tclient, false);
            }
        }

        public static void updateUser(string packet, TcpClient tclient)
        {
            packet = Security.Cleaner.cleanString(packet);
            string[] words = packet.Split(' ');
            string password = words[1], email = words[2];
            string pants, shirt, head;
            if (words[3].Contains("/"))
            {
                pants = words[3].Split('/')[0];
                shirt = words[3].Split('/')[1];
                head = words[3].Split('/')[2];
            }
            else
            {
                pants = words[3].Split(',')[0];
                shirt = words[3].Split(',')[1];
                head = words[3].Split(',')[2];
            }
            string sex = (words[6].ToString().Equals("Male") ? "M" : "F");
            string age = words[8].ToString();

            string mission = words[9].ToString();

            for (int i = 10; i < words.Length; i++)
            {
                if (i > 9) mission += " " + words[i];
            }

            //Stop invisibility
            if (pants == "" || pants == "0" || pants == "9") pants = "1";
            if (shirt == "" || shirt == "0" || shirt == "9") shirt = "1";
            if (head == "" || head == "0" || head == "9") head = "1";

            if (DBManager.database.getString("SELECT COUNT(*) FROM `users` WHERE `email` = '" + email + "' AND `name` != '" + tclient.userObject.username + "'") != "0")
            {
                tclient.sendData("ERROR That email is already registered!");
                return;
            }
            else
            {
                DBManager.database.noCommand("UPDATE `users` SET `password` = '" + password + "', `email` = '" + email + "', `age` = '" + age + "', `pants` = '" + pants + "', `shirt` = '" + shirt + "', `head` = '" + head + "', `sex` = '" + sex + "', `mission` = '" + mission + "' WHERE `name` = '" + tclient.userObject.username + "' LIMIT 1;");
            }
        }

        public static UserObject newObject(string username, string password, TcpClient tClient)
        {
            MySqlDataReader mysqlRead = DBManager.database.getCommand("SELECT * FROM `users` WHERE `name` = '" + username + "' AND `password` = '" + password + "' LIMIT 1").ExecuteReader();
            mysqlRead.Read();

            return new UserObject(mysqlRead["name"].ToString(), mysqlRead["password"].ToString(), mysqlRead["mission"].ToString(), mysqlRead["email"].ToString(), mysqlRead["sex"].ToString(), Convert.ToInt32(mysqlRead["pants"]), Convert.ToInt32(mysqlRead["shirt"]), Convert.ToInt32(mysqlRead["head"]), Convert.ToInt32(mysqlRead["rank"]), Convert.ToInt32(mysqlRead["age"]), tClient);
        }

    }
}
