using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using CommonFunc;


public class Common
{
    public static string lblmsg;
    public static string ImageName;
    public List<SelectListItem> Language { get; set; }
    public string ddlLanguage { get; set; }
    public string ID { get; set; }
    public string hdlang { get; set; }
    public static List<gallerylist> GalleryList { get; set; }
    public static List<SelectListItem> FillSelectList(string query, string Text, string Value, string DefaultSelectedCharcter = "")
    {
        DataLayer obj = DataLayer.Instance;
        List<SelectListItem> obj1 = new List<SelectListItem>();
        if (DefaultSelectedCharcter != null && DefaultSelectedCharcter != "")
        {
            obj1.Add(new SelectListItem { Text = DefaultSelectedCharcter, Value = "0" });
        }
        DataTable dtlanguage = obj.SelectDatatable(query);
        if (dtlanguage != null && dtlanguage.Rows.Count > 0)
        {
            foreach (DataRow row in dtlanguage.Rows)
            {
                obj1.Add(new SelectListItem { Text = HttpUtility.HtmlDecode(row[Text].ToString().Trim()), Value = HttpUtility.HtmlDecode(row[Value].ToString().Trim()) });
            }
        }
        return obj1;
    }
    public static List<SelectListItem> FillSelectList<T>(List<T> Data, string Text, string Value, string DefaultSelectedCharcter = "")
    {
        List<SelectListItem> obj1 = new List<SelectListItem>();
        if (Data != null && Data.Count() > 0)
        {
            foreach (var row in Data)
            {
                obj1.Add(new SelectListItem { Text = Convert.ToString(row.GetType().GetProperty(Text).GetValue(row, null)).HtmlDecode(), Value = Convert.ToString(row.GetType().GetProperty(Value).GetValue(row, null)).HtmlDecode() });
            }
        }
        return obj1;
    }
    public static List<SelectListItem> FillSelectListManual(params string[] Items)
    {
        List<SelectListItem> obj1 = new List<SelectListItem>();
        foreach (var row in Items)
        {
            obj1.Add(new SelectListItem { Text = HttpUtility.HtmlDecode(row.ToString().Trim()), Value = HttpUtility.HtmlDecode(row.ToString().Trim()) });
        }
        return obj1;
    }
    // get check box list item selected
    public static List<SelectListItem> ChkSelectList_Update(List<SelectListItem> items, string seleted)
    {
        DataLayer obj = DataLayer.Instance;
        if (items != null && items.Count > 0)
        {
            foreach (var item in items)
            {
                bool select = (("," + seleted + ",").Contains("," + item.Value.ToString().Trim() + ",") == true) ? true : false;
                item.Selected = select;
            }
        }
        return items;
    }
    public static List<T> ChkSelectList_Update<T>(List<T> items, string seleted)
    {
        DataLayer obj = DataLayer.Instance;
        if (items != null && items.Count > 0)
        {
            foreach (var item in items)
            {
                bool select = (("," + seleted + ",").Contains("," + item.GetType().GetProperty("Value").GetValue(item,null).ToString().Trim() + ",") == true) ? true : false;
                item.GetType().GetProperty("Selected").SetValue(item, select);
            }
        }
        return items;
    }
    public static bool UploadMultipleFiles(IEnumerable<HttpPostedFileBase> flFile,  string filepath, string format = "", float width = 0, float height = 0)
    {
        bool result = false;
        try
        {
            if (flFile != null)
            {
                ImageName = "";
                //foreach (HttpPostedFileBase file in flGallerys)
                foreach (HttpPostedFileBase file in flFile)
                {
                    if (file != null)
                    {
                        string bannerimagetemp = "";
                        var vald = CommonFunc.ValidationFunc.ImageValidate(file, format, width, height);
                        if (vald.isValid == false)
                        {
                            lblmsg = vald.Message;
                        }
                      
                        string strprofileimagenew = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
                        strprofileimagenew = ReplaceFunc.Alias(strprofileimagenew);
                        string strprofileimageext = System.IO.Path.GetExtension(file.FileName);
                        bannerimagetemp = strprofileimagenew + strprofileimageext;
                        //bannerimage += bannerimagetemp + ",";
                        ImageName += bannerimagetemp + ",";
                        file.SaveAsOptimised(HttpContext.Current.Server.MapPath(filepath + "/" + bannerimagetemp.ToString().Trim()));

                    }
                }
                ImageName = ImageName.Substring(0, ImageName.Length - 1);
                result = true;
            }
        }
        catch(Exception ex)
        {
            result = false;
        }
        
            return result;
       
    }
    
    public static string getLanguageCode()
    {
        string Language = "en";
        if (HttpContext.Current.Session["Language"] == null || HttpContext.Current.Session["Language"].ToString().Trim() == "")
        {
            if (HttpContext.Current.Request.Cookies["Language"] != null && HttpContext.Current.Request.Cookies["Language"].Value.ToString().Trim() != "")
            {
                HttpContext.Current.Session["Language"] = HttpContext.Current.Request.Cookies["Language"].Value.ToString().Trim();
                Language = HttpContext.Current.Session["Language"].ToString().Trim();
            }

        }
        else
        {
            Language = HttpContext.Current.Session["Language"].ToString().Trim();
        }

        System.Threading.Thread.CurrentThread.CurrentCulture =
                 new System.Globalization.CultureInfo(Language);
        System.Threading.Thread.CurrentThread.CurrentUICulture =
            new System.Globalization.CultureInfo(Language);
        return Language;
    }
    public static List<SelectListItem> loadLanguage()
    {
        DataLayer obj = DataLayer.Instance;
        List<SelectListItem> obj1 = new List<SelectListItem>();
        string query = "select Language,LanguageCode from tblLanguage where status=1";
        DataTable dtlanguage = obj.SelectDatatable(query);
        if (dtlanguage != null && dtlanguage.Rows.Count > 0)
        {
            foreach (DataRow row in dtlanguage.Rows)
            {
                obj1.Add(new SelectListItem { Text = row["Language"].ToString().Trim(), Value = row["LanguageCode"].ToString().Trim() });
            }
        }
        return obj1;
    }
    // Add images to Editor
    public static void UploadEditorImage(string ContentPart, string Path)
    {
        var aStringBuilder = new StringBuilder(ContentPart);
        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        document.LoadHtml(ContentPart);
        HtmlAgilityPack.HtmlNodeCollection collection1 = document.DocumentNode.SelectNodes("//img");
        if (collection1 != null)
        {
            int i = 0;
            foreach (HtmlAgilityPack.HtmlNode link in collection1)
            {
                string target = link.Attributes["src"].Value;
                if ((target.Length > 64) && target.Contains("base64,"))
                {
                    string[] t = target.Split(',');

                    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(t[1])))
                    {
                        using (Bitmap bm2 = new Bitmap(ms))
                        {
                            string strgooglemapimageNew = Path + i.ToString().Trim() + Convert.ToString(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString()) + ".jpg";
                            string imagepath = HttpContext.Current.Server.MapPath("/" + strgooglemapimageNew);
                            bm2.Save(imagepath);
                            link.Attributes["src"].Value = strgooglemapimageNew;
                            aStringBuilder.Replace(target, ConfigurationManager.AppSettings["siteurl"].ToString() + strgooglemapimageNew);
                            i++;
                        }
                    }
                }
            }
        }
    }

    // Update AltTag and Title Tag
    public static int updateGallery(int id, string title, string alt, int displayorder, string language)
    {
        DataLayer obj = DataLayer.Instance;
        int i = 0;
        SqlParameter[] perm = new SqlParameter[5];
        perm[0] = new SqlParameter("@GalleryID", id);
        perm[1] = new SqlParameter("@ImageTitle", HttpUtility.HtmlEncode(title));
        perm[2] = new SqlParameter("@ImageAltTag", HttpUtility.HtmlEncode(alt));
        perm[3] = new SqlParameter("@Language", HttpUtility.HtmlEncode(language));
        perm[4] = new SqlParameter("@DisplayOrder", displayorder);
        DataTable success = obj.ExecuteStoreProcedure("proc_tblGallery_T", perm);
        if (success != null)
        {
            i = 1;
        }
        return i;
    }

    //Upload multiple images for Gallery Section
    public static string UploadData(HttpFileCollectionBase flGallerys, string sid, string language, string GalleryType)
    {
        DataLayer obj = DataLayer.Instance;
        string result = "Error, Invalid";
        string gid = "";
        if (Int32.Parse(sid) > 0)
        {

            string bannerimage = "";
            if (flGallerys != null)
            {
                //foreach (HttpPostedFileBase file in flGallerys)
                for (int m = 0; m < flGallerys.Count; m++)
                {
                    HttpPostedFileBase file = flGallerys[m];
                    if (file != null)
                    {
                        string bannerimagetemp = "";
                        var val = ValidationFunc.ImageValidate(file, ".png, .jpg, .jpeg, .gif", 800, 720);
                        if (val.isValid == false)
                        {
                            return val.Message;
                        }


                        bannerimagetemp = UploadFunc.CustomFileName(file);
                        bannerimage += bannerimagetemp + ",";

                    }
                }

                if (bannerimage.Length > 0)
                {
                    bannerimage = bannerimage.Substring(0, bannerimage.Length - 1);
                }

                var GalleryArray = bannerimage.Split(',');
                int i = 0;

                for (int m = 0; m < flGallerys.Count; m++)
                {
                    HttpPostedFileBase file = flGallerys[m];
                    if (file != null)
                    {
                        string imagename = GalleryArray[i];
                        int index = imagename.LastIndexOf(".");
                        string image = imagename.Substring(0, imagename.LastIndexOf("."));
                        string imageextension = imagename.Substring(index, imagename.Length - index);
                        string FreeSize = image + "-free" + imageextension;
                        string Gallery240 = image + "-240" + imageextension;
                        string Gallery440 = image + "-440" + imageextension;
                        file.SaveAs(HttpContext.Current.Server.MapPath("/" + ConfigurationManager.AppSettings["Galleryimage"].ToString().Trim() + FreeSize.ToString().Trim()));
                        //Add Images to Database
                        SqlParameter[] perm = new SqlParameter[6];
                        perm[0] = new SqlParameter("@ID", Int32.Parse(sid));
                        perm[1] = new SqlParameter("@Small", HttpUtility.HtmlEncode(Gallery240));
                        perm[2] = new SqlParameter("@Large", HttpUtility.HtmlEncode(Gallery440));
                        perm[3] = new SqlParameter("@FreeSize", HttpUtility.HtmlEncode(FreeSize));
                        perm[4] = new SqlParameter("@nid", DbType.Int32);
                        perm[4].Direction = ParameterDirection.Output;
                        perm[5] = new SqlParameter("@Template", HttpUtility.HtmlEncode(GalleryType));
                        DataTable success = obj.ExecuteStoreProcedure("Proc_tblGallery", perm);
                        //get id of added imges
                        gid += perm[4].Value.ToString() + ",";
                        if (success != null)
                        {
                            string imagepath = HttpContext.Current.Server.MapPath("/" + ConfigurationManager.AppSettings["Galleryimage"].ToString().Trim());
                            //Crop images
                            UploadFunc.resizeImageCrop(imagepath, imagepath, Gallery240, FreeSize, 240, 200);
                            UploadFunc.resizeImageCrop(imagepath, imagepath, Gallery440, FreeSize, 440, 400);
                        }
                        i++;
                    }
                }
                result = "success";
                gid = gid.Substring(0, gid.Length - 1);
                // Get images detail of uploaded images
                string selectGalleryQuery = string.Format(@"select t1.*,isnull(t2.ID,0) as ID_T,t2.GAlleryID,t2.ImageAltTag,t2.ImageTitle,t2.Language,t2.createdate as createddate,t2.updatedate as updateddate from tblGallery t1 left outer join tblGallery_T t2 on (t1.ID=t2.GalleryID) where t1.PageID={0}  and 
                    (t2.Language = (select IIF(EXISTS(SELECT 1 FROM tblGallery_T where GalleryID = t1.ID and language = '{2}'), '{2}', 'en'))  or t2.Language is null) and  t1.Template='{1}' and t1.ID in ({3})", sid, GalleryType, language, gid);
                DataTable dt = obj.SelectDatatable(selectGalleryQuery);
                // Fill data to GalleryList
                GalleryList = dt.AsEnumerable().Select(row =>
                    new gallerylist
                    {
                        ID = Convert.ToString(row.Field<int>("ID")),
                        ID_T = Convert.ToString(row.Field<int>("ID_T")),
                        ImageName = row.Field<string>("SmallImage"),
                        DisplayOrder = row.Field<int>("DisplayOrder"),
                        AltTag = row.Field<string>("ImageAltTag"),
                        Title = row.Field<string>("ImageTitle"),
                        EncryptdID = Convert.ToString(row.Field<int>("ID")).Encrypt()
                    }).ToList();
            }

        }
        return result;

    }

    //
    

}
public class gallerylist
{
    public string ID { get; set; }
    public string ID_T { get; set; }
    public string ImageName { get; set; }
    public string AltTag { get; set; }
    public string Title { get; set; }
    public int DisplayOrder { get; set; }
    public string EncryptdID { get; set; }
}