using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Westwind.BusinessObjects;
using System.Text;


namespace ScriptCallbacks.BusinessObjects
{
    /// <summary>
    /// The Chat Message Business object used to load and manage
    /// chat messages.
    /// </summary>
    public class busChatMessage : wwBusiness<ChatmessagesRow>
    {
        public busChatMessage()
        {
            this.ConnectionString = this.ConnectionString = ConfigurationManager.ConnectionStrings["AjaxAspNet"].ConnectionString;
            this.ConnectType = ServerTypes.SqlServer;
            this.DataRowUpdateMode = DataRowUpdateModes.OptimizedByPk;
            this.Tablename = "ChatMessages";
            this.DataRowUpdateFieldFilter = "Pk"; // Don't update PK field
            this.PkField = "Pk";
            this.PkType = PkFieldTypes.intType;
        }

        /// <summary>
        /// No Ids created - AutoInc used in Database
        /// </summary>
        /// <returns></returns>
        public override object CreateNewId()
        {
            return -1;
        }


        /// <summary>
        /// Returns a Table called TMessages for the message since a given time
        /// and chat id.
        /// </summary>
        /// <param name="Since"></param>
        /// <param name="ChatId"></param>
        /// <returns></returns>
        public int GetMessages(DateTime Since,string ChatId)
        {
            return this.Execute("select * from ChatMessages where ChatId=@ChatID AND Time>=@Time order by Time",
                                "TMessages",this.CreateParameter("@ChatId",ChatId),this.CreateParameter("@Time",Since));
        }

        /// <summary>
        /// Returns a table called TMessages that returns the last x messges for a give chat
        /// </summary>
        /// <param name="MessageCount"></param>
        /// <param name="ChatId"></param>
        /// <returns></returns>
        public int GetMessages(int MessageCount,string ChatId)
        {
            return this.Execute("select TOP " + MessageCount.ToString() +   
                               @"* from ChatMessages where ChatId=@ChatID order by Time DESC",
                               "TMessages", this.CreateParameter("@ChatId", ChatId));
        }

        public string GetMessagesHtml(DateTime Since, string ChatId)
        {
            if (this.GetMessages(Since, ChatId) < 0)
                return null;

            StringBuilder sb = new StringBuilder();

            ChatmessagesRow Message = new ChatmessagesRow();
            foreach (DataRow row in this.DataSet.Tables["TMessages"].Rows)
            {
                Message.SetDataRow(row);

                //if (ChatId == Message.)
                //    sb.Append("<div class='MessageWrapperMe'>\r\n");
                //else
                sb.Append("<div class='MessageWrapper'>\r\n");
                sb.Append("<div class='MessageAuthor'>" + Message.Sender + " says:</div>");
                sb.Append("<div class='Message'>" + Message.Message + "</div>\r\n");
                sb.Append("</div>");
            }

            return sb.ToString();
        }

        public int GetRecentUsers(string ChatId)
        {
            return this.Execute("select Sender,LastOn,LastPost from ChatActivity where LastOn > @Time and ChatId = @ChatId order by Sender",
                                "TUsers", this.CreateParameter("@Time", DateTime.UtcNow.AddMinutes(-1)), this.CreateParameter("@ChatId", ChatId));
        }


        public void WriteChatActivity(string ChatId, string Sender,ChatActivityTypes ChatActivityType) 
        {
            int Result = 0;
            if (Sender == "" || ChatId == "")
                return;

            if (ChatActivityType == ChatActivityTypes.ReadMessages)
                Result = this.ExecuteNonQuery("update ChatActivity " +
                                              "set LastOn=@Time " +
                                              "where ChatId=@ChatId AND Sender=@Sender",
                            this.CreateParameter("@ChatId", ChatId),
                            this.CreateParameter("@Sender", Sender),
                            this.CreateParameter("@Time",DateTime.UtcNow) );

            else if (ChatActivityType == ChatActivityTypes.WriteMessage)
                Result = this.ExecuteNonQuery("update ChatActivity " +
                                              "set LastOn=@Time,LastPost=@Time " +
                                              "where ChatId=@ChatId AND Sender=@Sender",
                            this.CreateParameter("@ChatId", ChatId),
                            this.CreateParameter("@Sender", Sender),
                            this.CreateParameter("@Time",DateTime.UtcNow) );                                  
            if (Result < 1)
                this.ExecuteNonQuery("insert into ChatActivity " +
                                  "(ChatId,Sender,LastOn,LastPost,SignedOn) VALUES " +
                                  "(@ChatId,@Sender,@Time,@Time,@Time)",
                            this.CreateParameter("@ChatId", ChatId),
                            this.CreateParameter("@Sender", Sender),
                            this.CreateParameter("@Time", DateTime.UtcNow));                                  

        }

        /// <summary>
        /// Returns a list of active chats in a table called TChats
        /// </summary>
        /// <returns></returns>
        public int GetChatList()
        {
            return this.Execute("select Max(ChatId) as ChatId from ChatActivity where LastOn > @Time group by ChatId",
                                "TChats", 
                                this.CreateParameter("@Time", DateTime.UtcNow.AddMinutes(-1) ) );
        }

        /// <summary>
        /// Removes messages older than 15 minutes
        /// </summary>
        public void ClearMessages()
        {
            this.ExecuteNonQuery("delete from " + this.Tablename + " WHERE Time < @Time",
                                  this.CreateParameter("@Time",DateTime.UtcNow.AddMinutes(-15)) );

            this.ExecuteNonQuery("delete from ChatActivity WHERE LastOn < @Time",
                       this.CreateParameter("@Time", DateTime.UtcNow.AddMinutes(-15)));

        }

   }

   public enum ChatActivityTypes
   {
       ReadMessages,
       WriteMessage,
       ChatEntered
   }
}