using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.Drawing;

using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;

/// <summary>
/// Summary description for Utility
/// </summary>
public static class Utility
{

//    private static List<string> _siteSettings = null;
    public static void FlushSiteSettings() { _siteSettings = null;  }
    private static Dictionary<string, string> _siteSettings = null;
    public static Dictionary<string, string> SiteSettings {
        get {
            if (_siteSettings == null)
            {
                _siteSettings = new Dictionary<string, string>();
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SabrinContent"].ToString()))
                {
                    string sql = "select * from SiteSettings";
                    connection.Open();
                    IDataReader reader = SqlHelper.ExecuteReader(CommandType.Text, sql);
                    while (reader.Read())
                    {
                        _siteSettings.Add(reader["SettingName"].ToString(),
                                        reader["SettingValue"].ToString());
                    }
                    connection.Close();
                }
            }

            return _siteSettings;
        }
    }

    public static string QuickVerifyCode() { return "GSQC02202"; }

    public static bool IsNull(object val)
    {
        if (val != null)
            return IsNull(val, val.GetType());

        return true;
    }

    public static bool IsNull(object val, Type ty)
    {
        switch (ty.Name)
        {
            case "DateTime":
                //return DateTime.MinValue == (DateTime)val;
                return MSDateTime.MinDate >= (DateTime)val;

            case "DBNull":
                return true;

            case "String":
                return string.IsNullOrEmpty(val.ToString());

            case "Byte":
            case "Int16":
            case "Int32":
            default:
                return val == null;
        }
    }

    private static TripleDESCryptoServiceProvider GetDES()
    {
        string password = "astechencrypt1";
        TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider hashmd5;
        byte[] pwdhash;
        hashmd5 = new MD5CryptoServiceProvider();
        pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
        hashmd5 = null;
        des.Key = pwdhash;
        des.Mode = CipherMode.ECB;
        return des;
    }

    public static string Encrypt(string Input)
    {
        byte[] buff;
        string ret = "";
        TripleDESCryptoServiceProvider des = GetDES();
        buff = ASCIIEncoding.ASCII.GetBytes(Input);
        ret = Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length));
        return ret;
    }

    public static string Decrypt(string Input)
    {
        byte[] buff = Convert.FromBase64String(Input);
        TripleDESCryptoServiceProvider des = GetDES();
        string ret = ASCIIEncoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(buff, 0, buff.Length));
        return ret;
    }

    public static String XMLize(Object c, Type[] t)
    {
        String XmlizedString = null;
        try
        {
            XmlSerializer xs = GetSerializer(c.GetType(), t);
            StringWriter sw = new StringWriter();
            xs.Serialize(sw, c);
            XmlizedString = sw.ToString();
            XmlizedString = XmlizedString.Replace("\r", "");
            XmlizedString = XmlizedString.Replace("\n", "");
        }
        catch (Exception e)
        {
            throw e;
        }
        return XmlizedString;
    }

    /// <summary>
    /// Given an object return a string representing an XML object
    /// that is consistent with sql server 2005 xml data type
    /// </summary>
    /// <param name="c">Object to be XMLized</param>
    /// <returns>XML string</returns>
    public static String XMLize(Object c)
    {
        return XMLize(c, null);
    }

    public static object Deserialize(Type t, string xml)
    {
        return Deserialize(t, null, xml);
    }

    public static XmlSerializer GetSerializer(Type t, Type[] ts)
    {
        Hashtable serializers = (Hashtable)MSCacheManager.Item("serializers");
        if (Utility.IsNull(serializers))
        {
            serializers = new Hashtable();
        }
        string key = t.ToString();
        XmlSerializer xs = (XmlSerializer)serializers[key];
        if (Utility.IsNull(xs))
        {
            if (Utility.IsNull(ts))
                xs = new XmlSerializer(t);
            else
                xs = new XmlSerializer(t, ts);
            if (serializers.Contains(key))
                serializers.Remove(key);
            serializers.Add(key, xs);
            MSCacheManager.Insert("serializers", serializers, -1);
        }
        return xs;
    }

    public static object Deserialize(Type t, Type[] ts, string xml)
    {
        XmlSerializer xs = GetSerializer(t, ts);
        Object o = null;
        if (xml.Length == 0)
            return null;
        else
            o = xs.Deserialize(new StringReader(xml));

        return o;
    }

    public static MSUser User
    {
        get
        {
            return (MSUser)HttpContext.Current.Session["User"];
        }
    }

    public static string EncodeEncrypt(object o)
    {
        return HttpUtility.UrlEncode(Encrypt(o.ToString()));
    }

    public static Control FindControl(ControlCollection controls, string ID)
    {
        Control temp = null;
        foreach (Control c in controls)
        {
            if (!IsNull(c.ID) && c.ID.Equals(ID, StringComparison.InvariantCultureIgnoreCase))
                temp = c;
        }

        if (Utility.IsNull(temp))
        {
            foreach (Control c2 in controls)
            {
                temp = FindControl(c2.Controls, ID);
                if (!Utility.IsNull(temp))
                    return temp;
            }
        }

        return temp;
    }

    public static Byte[] FileToByteArray(string filename)
    {

        StreamReader sr = new StreamReader(System.AppDomain.CurrentDomain.BaseDirectory + filename);
        byte[] stream = StreamToByteArray(sr.BaseStream);
        return stream;
    }

    public static Byte[] StreamToByteArray(Stream stream)
    {
        Int32 streamLength = (Int32)stream.Length;
        Byte[] bytearray = new Byte[streamLength];
        stream.Read(bytearray, 0, streamLength);
        stream.Close();
        return bytearray;
    }

    public static Size CalculateRescaleDimensions(int MaxWidth, int MaxHeight, int CurrentWidth, int CurrentHeight, bool UseSmallestDimension)
    {

        double scale = (double)MaxWidth / (double)CurrentWidth;
        double scale2 = (double)MaxHeight / (double)CurrentHeight;

        double tScale = 1;
        if (UseSmallestDimension)
            tScale = (scale > scale2 ? scale2 : scale);
        else tScale = (scale > scale2 ? scale : scale2);

        Size newSize = new Size();
        newSize.Width = (int)(CurrentWidth * tScale);
        newSize.Height = (int)(CurrentHeight * tScale);

        int diffW = newSize.Width - MaxWidth;
        int diffH = newSize.Height - MaxHeight;

        if (diffH < 1) diffH = 0;
        if (diffW < 1) diffW = 0;

        if (diffH > 0 || diffW > 0)
        {
            if (diffH > diffW)
            {
                diffH *= (int)(diffH / diffW);
            }
            else
            {
                diffW *= (int)(diffW / diffH);
            }
            newSize.Height -= diffH;
            newSize.Width -= diffW;
        }
        return newSize;
    }

    public static Byte[] ScaleImage(byte[] image, int width, int height)
    {
        Bitmap bm = new Bitmap(new MemoryStream(image));
        int originalWidth = bm.Width;
        int originalHeight = bm.Height;
        //i did it already - KS
        Size newDims = CalculateRescaleDimensions(width, height, originalWidth, originalHeight, true);
        System.Drawing.Image img = bm.GetThumbnailImage(newDims.Width, newDims.Height, null, (IntPtr)0);

        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms.ToArray();
    }

    public static string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }

    public static bool IsAdmin
    {
        get
        {
            return (!Utility.IsNull(HttpContext.Current.Session["admin"]) && Convert.ToBoolean(HttpContext.Current.Session["admin"]) == true);
        }
    }

}
