using System;
using System.IO;
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 System.Net;
using System.Net.Mail;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Globalization;

namespace digioz
{
    /// <summary>
    /// Utility class for IO and Web
    /// </summary>
    public class Utility
    {
        public Utility()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static bool IsNumeric(string psInputString)
        {
            return Regex.IsMatch(psInputString, "^[0-9]+$");
        }

        public static string GetWebPageContent(string lsPage)
        {
            string lsOutput = String.Empty;

            try
            {
                HttpWebRequest loHttpWebRequest = (HttpWebRequest)WebRequest.Create(lsPage);
                HttpWebResponse loHttpWebResponse = (HttpWebResponse)loHttpWebRequest.GetResponse();
                Stream loReceiveStream = loHttpWebResponse.GetResponseStream();
                System.Text.Encoding loEncode = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader loReadStream = new StreamReader(loReceiveStream, loEncode);

                lsOutput = loReadStream.ReadToEnd();
                loReceiveStream.Close();
                loReadStream.Close();
            }
            catch
            {
                lsOutput = String.Empty;
            }

            return lsOutput;
        }

        public static string ConvertHtmlToPlainText(string psHTMLText)
        {
            string lsOutput = psHTMLText;
            lsOutput = System.Text.RegularExpressions.Regex.Replace(psHTMLText, "<[^>]*>", string.Empty);
            lsOutput = lsOutput.Replace("'", "''");
            lsOutput = lsOutput.Replace("<", "&#60;");
            lsOutput = lsOutput.Replace(">", "&#62;");
            lsOutput = lsOutput.Replace("\"", "&#34;");
            lsOutput = lsOutput.Replace("\n", "<br />");
            //lsOutput = lsOutput.Replace("--", "&#150;&#150;");
            return lsOutput;
        }

        /// <summary>
        /// This function only filters input for potentially dangerous HTML
        /// No encoding is performed as some controls (some properties)
        /// have built-in encoding
        /// </summary>
        /// <param name="psHTMLText"></param>
        /// <returns></returns>
        public static string ConvertHtmlFilterInput(string psHTMLText)
        {
            string lsOutput = psHTMLText;
            lsOutput = System.Text.RegularExpressions.Regex.Replace(psHTMLText, "<[^>]*>", string.Empty);
            return lsOutput;
        }

        /// <summary>
        /// Encode the new line sequence for display
        /// </summary>
        /// <param name="psHTMLText"></param>
        /// <returns></returns>
        public static string EncodeNewLine(string psHTMLText)
        {
            string lsOutput = psHTMLText;
            lsOutput = lsOutput.Replace(Environment.NewLine, "<br />");
            return lsOutput;
        }

        public static string GetFileContents(string lsPath)
        {
            string lsContents = null;
            StreamReader loStreamReader = default(StreamReader);

            try
            {
                loStreamReader = new StreamReader(lsPath);
                lsContents = loStreamReader.ReadToEnd();
                loStreamReader.Close();
            }
            catch
            {
                lsContents = String.Empty;
            }

            return lsContents;
        }

        public static bool SaveTextToFile(string lsString, string lsPath)
        {
            bool lbSuccess = false;
            StreamWriter loStreamWriter = default(StreamWriter);

            try
            {
                loStreamWriter = new StreamWriter(lsPath);
                loStreamWriter.Write(lsString);
                loStreamWriter.Close();
                lbSuccess = true;
            }
            catch
            {
                lbSuccess = false;
            }

            return lbSuccess;
        }

        public static bool AppendTextToFile(string lsString, string lsPath)
        {
            StreamWriter loStreamWriter = null;
            bool lbSuccess = false;

            // Create the file if it does not exist 
            if (File.Exists(lsPath) == false)
            {
                loStreamWriter = File.CreateText(lsPath);
                loStreamWriter.Flush();
                loStreamWriter.Close();
            }

            try
            {
                loStreamWriter = File.AppendText(lsPath);
                loStreamWriter.Write(lsString);
                lbSuccess = true;
            }
            catch
            {
                lbSuccess = false;
            }
            finally
            {
                loStreamWriter.Flush();
                loStreamWriter.Close();
            }

            return lbSuccess;
        }

        public static int UserId(Page poPage)
        {
            int liUserID = 0;
            if (poPage.Session["userid"] != null &&
                Convert.ToString(poPage.Session["userid"]) != String.Empty)
            {
                liUserID = Convert.ToInt32(poPage.Session["userid"]);
            }
            return liUserID;
        }

        /// <summary>
        /// Display a popup message
        /// </summary>
        /// <param name="poPage"></param>
        /// <param name="psMessage"></param>
        public static void ShowMessage(Page poPage,
                                       string psMessage)
        {
            string lsScriptKey = string.Format("{0}:{1}",
                                              psMessage, poPage.UniqueID);

            if ( (!string.IsNullOrEmpty(psMessage)) &&
                 (!poPage.IsStartupScriptRegistered(lsScriptKey)))
            {
                
                string lsScript = 
                       @"<script language=""JavaScript"">
                       <!--
                          alert(""%%POPUP_MESSAGE%%"");
                       // -->
                       </script>";
                lsScript = lsScript.Replace("%%POPUP_MESSAGE%%", psMessage);
                poPage.RegisterStartupScript(lsScriptKey, lsScript);
                
            }

        }

        /// <summary>
        /// Prompt user with various messages after login
        /// Session["PromptShown"] = null -> not logged in
        /// Session["PromptShown"] = NO   -> logged in, prompt pending
        /// Session["PromptShown"] = YES  -> user already prompted.
        ///                                  or no prompt needed.
        /// </summary>
        /// <param name="poPage"></param>
        public static void LoginPrompt(Page poPage)
        {
            int liUserID = Utility.UserId(poPage);
            if ( (poPage.Session["PromptShown"] != null) &&
                 (liUserID > 0))
            {
                // We need to prompt the user
                if (Convert.ToString(poPage.Session["PromptShown"]) == "NO")
                {
                    if (PrivateMessageManagement.GetUnReadMessagesCount(liUserID) > 0)
                    {
                        Utility.ShowMessage(poPage, "You have unread message!");
                    }

                    if (FriendsManagement.GetNeedApprovedFriendsCount(liUserID) > 0)
                    {
                        Utility.ShowMessage(poPage, "Need Approved Friends!");
                    }

                    poPage.Session["PromptShown"] = "YES";
                }

            }
        }

        public static CultureInfo ResolveCulture()
        {
            string[] languages = HttpContext.Current.Request.UserLanguages;

            if (languages == null || languages.Length == 0)
                return null;

            try
            {
                string language = languages[0].ToLowerInvariant().Trim();
                return CultureInfo.CreateSpecificCulture(language);
            }
            catch (ArgumentException)
            {
                return null;
            }
        }

        public static RegionInfo ResolveCountry()
        {
            CultureInfo culture = ResolveCulture();

            if (culture != null)
            {
                return new RegionInfo(culture.LCID);
            }

            return null;
        }

        public static Visitor GetVisitor()
        {
            Visitor visitor = new Visitor();
            visitor.Country = ResolveCountry().DisplayName;
            visitor.IP = GetVisitorIp();
            visitor.OS = GetOS();
            visitor.Browser = HttpContext.Current.Request.Browser.Browser;

            return visitor;
        }

        private static string GetOS()
        {
            string os = String.Empty;
            string userAgent = HttpContext.Current.Request.UserAgent;

            if (userAgent.IndexOf("Windows NT 5.0") > 0)
            {
                os = "Windows 2000";
            }
            else if (userAgent.IndexOf("Windows NT 5.1") > 0)
            {
                os = "Windows XP";
            }
            else if (userAgent.IndexOf("Windows NT 5.2") > 0)
            {
                os = "Windows Server 2003";
            }
            else if (userAgent.IndexOf("Windows NT 6.0") > 0)
            {
                os = "Windows Vista";
            }
            else if (userAgent.IndexOf("Windows NT 6.1") > 0)
            {
                os = "Windows 7";
            }
            else if (userAgent.IndexOf("Macintosh") > 0)
            {
                os = "Mac OS";
            }
            else if (userAgent.IndexOf("Linux") > 0)
            {
                os = "Linux";
            }
            else
            {
                os = "Other Operating System";
            }

            return os;
        }

        private static string GetVisitorIp()
        {
            string visitorsIp = string.Empty;

            if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                //To get the IP address of the machine and not the proxy
                visitorsIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
            {
                visitorsIp = HttpContext.Current.Request.UserHostAddress;
            }

            return visitorsIp;
        }

        public class Encryption64
        {
            //private byte[] key = {};
            //private byte[] IV = {10, 20, 30, 40, 50, 60, 70, 80}; // it can be any byte value

            public static string Decrypt(string stringToDecrypt,
            string sEncryptionKey)
            {

                byte[] key = { };
                byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
                byte[] inputByteArray = new byte[stringToDecrypt.Length];

                try
                {
                    key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                    inputByteArray = Convert.FromBase64String(stringToDecrypt);

                    MemoryStream ms = new MemoryStream();
                    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();

                    Encoding encoding = Encoding.UTF8;
                    return encoding.GetString(ms.ToArray());
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            }

            public static string Encrypt(string stringToEncrypt,
            string sEncryptionKey)
            {

                byte[] key = { };
                byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
                byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)

                try
                {
                    key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                    inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                    MemoryStream ms = new MemoryStream();
                    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();

                    return Convert.ToBase64String(ms.ToArray());
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            }
        }

        public static class SendMail
        {
            public static bool SubmitMail(ContactInfo poContactInfo)
            {
                bool lbResponse = false;
                lbResponse = SubmitMail(poContactInfo.SenderEMail,
                                        poContactInfo.ContactEMail,
                                        poContactInfo.SenderSubject,
                                        poContactInfo.SenderMessage,
                                        poContactInfo.Attachment,
                                        poContactInfo.SMTPServer,
                                        poContactInfo.SMTPUsername,
                                        poContactInfo.SMTPPassword);
                return lbResponse;
            }

            public static bool SubmitMail(string lsFrom, string lsTo, string lsSubject, string lsMessage, string lsAttachment, string lsMailServer, string lsUsername, string lsPassword)
            {
                SmtpClient loSmtpClient = null;
                MailMessage loMessage = null;
                System.Net.Mail.Attachment loAttachment = null;
                bool lbResponse = false;

                try
                {
                    loSmtpClient = new SmtpClient(lsMailServer);
                    loSmtpClient.Credentials = new NetworkCredential(lsUsername, lsPassword);
                    loMessage = new MailMessage(lsFrom, lsTo, lsSubject, lsMessage);

                    loMessage.BodyEncoding = Encoding.UTF8;
                    loMessage.IsBodyHtml = true;
                    loMessage.Priority = MailPriority.Normal;
                    
                    if (lsAttachment.Length > 0)
                    {
                        loAttachment = new System.Net.Mail.Attachment(lsAttachment);
                        loMessage.Attachments.Add(loAttachment);
                    }

                    loSmtpClient.Send(loMessage);

                    lbResponse = true;
                }
                catch
                {
                    lbResponse = false;
                }

                return lbResponse;
             }
            
            
        }

    }
}
