using System;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.UI;
using System.Collections.Specialized;
using System.Web.Configuration;

namespace ExWeb
{
    public partial class Mod_Image : Mod
    {
        public static string Help_Description =
            "Anzeige eines Bildes\r\n\r\n"
            + "\r\nEin Verzeichnis .image wird angelegt und in diesem Verzeichnis werden die Miniaturansichten und die Vorschaubilder angelegt."
            + "\r\nDamit die Bilder mit Lightbox verwendet werden können, ist es erforderlich, die folgenden Zeilen im Header-Teil der ASPX-Datei einzufügen."
            + "<pre>"
            + "<script src=\"js/jquery-1.7.2.min.js\" type=\"text/javascript\"></script>\r\n"
            + "<script src=\"js/lightbox.js\" type=\"text/javascript\"></script>\r\n"
            + "<link href=\"css/lightbox.css\" rel=\"stylesheet\" />\r\n"
            + "<link href=\"css/screen.css\" rel=\"stylesheet\" />"
            + "</pre>"
            + "Unter Verwendung von LightBox von Lokesh Dhakar http://lokeshdhakar.com/projects/lightbox2/";

        public static string[][] Help_Attributes = new string[][]
        {
            // Attribut, Wert, DefaultWert, Optional, Hilfe
            new string[] {"Image","file","","","Name des Bildes","Image=\"myimage.png\""},
            new string[] {"PathToImage","path","/","opt","Verzeichnis","Path=\"/meineBilder\""},
            new string[] {"Thumb", "int", "200","opt","Größe der Miniaturansicht","Thumb=\"300\""},
            new string[] {"Preview","int", "640","opt","Größe des Vorschaubildes","Preview=\"800\""},
            new string[] {"Title","string", "","opt","Titel","Title=\"Ausflug\""},
            new string[] {"UseLightBox","0 1", "0","opt","Anzeige der Vorschau mit LightBox","UseLightBox=\"1\""},
        };
        public static string PathToImg = ".images";
        public static string z_thumb_prefix = "z_t_";
        public static string z_preview_prefix = "z_p_"; 
        string _Image = "";
        public string Image
        {
            set
            {
                _Image = value;
            }
        }
        string _Path = "/";
        public string PathToImage
        {
            set
            {
                if (!value.EndsWith("/")) value += "/";
                _Path = value.ToLower();
            }
        }
        int z_thumb_dim = 200;
        public string Thumb
        {
            set
            {
                int.TryParse(value, out z_thumb_dim);
            }
        }
        int z_preview_dim = 640;
        public string Preview
        {
            set
            {
                int.TryParse(value, out z_preview_dim);
            }
        }
        string _Title = "";
        public string Title
        {
            set
            {
                _Title = value;
            }
        }
        bool _UseLighBox = false;
        public string UseLightBox
        {
            set
            {
                _UseLighBox = (value == "1");
            }
        }
        string GetImage(string Url, string Title, string Alt)
        {
            return "<img src=\"" + Url + "\" title=\"" + Title + "\" alt=\"" + Alt + "\">";
        }
        string GetFrame(string Images, bool bSet)
        {
            return
                "<div class=\"imageRow\">"
                + (bSet?"<div class=\"set\">":"")
                + Images
                + (bSet ? "</div>" : "" )
                + "</div>";
        }
        string GetLink(string Text, string NavigateUrl, bool UseLightBox, string Group)
        {
            return
                "<div class=\"single\">"
                + "<a href=\"" + NavigateUrl + "\"" + (UseLightBox ? "rel=\"lightbox" + (Group == "" ? "" : "[" + Group + "]") + "\"" : "") + ">" + Text + "</a>"
                + "</div>";
        }
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            SetPanelLayout(this.Controls);

            object oLightBoxUsed = Context.Items["LightBoxUsed"];
            if (oLightBoxUsed == null) return;
            string strLightBoxUsed = oLightBoxUsed.ToString();
            if (strLightBoxUsed == "1")
            {
                // Page.Controls.AddAt(0,new LiteralControl(LoadShScripts()));
            }
            Context.Items["LoadShScripts"] = "0";
        }
        protected new void Page_Init(object sender, EventArgs e)
        {
            NameValueCollection nvc = WebConfigurationManager.AppSettings;
            z_thumb_dim = int.Parse(nvc["Img_t"]); 
            z_preview_dim = int.Parse(nvc["Img_p"]);
        }
        protected new void Page_Load(object sender, EventArgs e)
        {
            Page.LoadComplete += new EventHandler(Page_LoadComplete);


            string AbsolutePath = Server.MapPath(_Path);
            if (!_Path.Contains(PathToImg))
                CreateImageDirectory(AbsolutePath + PathToImg);

            if (_Image == "") // Read all Pictures from Directory
            {
                string[] Files = Directory.GetFiles(AbsolutePath);
                for (int i = 0; i < Files.Length; i++)
                {
                    string Extension = Path.GetExtension(Files[i]);
                    if (Extension.StartsWith(".")) Extension = Extension.Substring(1);
                    Extension = Extension.ToLower();
                    if (IsInList(Extension, FILETYPE.IMAGE))
                    {
                        string FileName = Path.GetFileName(Files[i]);
                        if (!FileName.StartsWith("."))
                            _Image += (i == 0 ? "" : ",") + Path.GetFileName(Files[i]);
                    }
                }
            }
            PlaceHolder_Image.Controls.Clear();
            string[] Images = _Image.Split(new char[] { ',' });
            bool bSet = Images.Length > 1;
            string s = "";
            for (int i = 0; i < Images.Length; i++)
            {
                CreateImage(AbsolutePath, z_thumb_prefix, Images[i], z_thumb_dim);
                CreateImage(AbsolutePath, z_preview_prefix, Images[i], z_preview_dim);
                string ImageUrl = _Path + PathToImg + "/" + z_thumb_prefix + ChangeExtensionToJpg(Images[i]);
                string NavigateUrl = _Path + PathToImg + "/" + z_preview_prefix + ChangeExtensionToJpg(Images[i]);
                s += GetLink(GetImage(ImageUrl, _Title, ""), NavigateUrl, _UseLighBox, this.ID);
            }
            s = GetFrame(s, bSet);
            PlaceHolder_Image.Controls.Add(new LiteralControl(s));
        }

        protected string LoadLightBoxScripts()
        {
            string s =
                "<script src='js/jquery-1.7.2.min.js' type='text/javascript'></script>"
                + "<script src='js/lightbox.js' type='text/javascript'></script>"
                + "<link href='css/lightbox.css' rel='stylesheet' />"
                + "<link href='css/screen.css' rel='stylesheet' />";
            return s;
        }
        public static string ChangeExtensionToJpg(string ImageFileName)
        {
            string Extension = Path.GetExtension(ImageFileName).ToLower();
            if (Extension.Length == 0) return ImageFileName;
            if (Extension == ".jpg")
                return ImageFileName;
            else
                return ImageFileName.ToLower().Replace(Extension, ".jpg");
        }
        public static void CreateImageDirectory(string AbsolutePath)
        {
            if (!Directory.Exists(AbsolutePath))
            {
                Directory.CreateDirectory(AbsolutePath);
            }
        }
        public static void CreateImage(string AbsolutePath, string Prefix, string Pic, int PixelSize)
        {
            string PictureName = Path.GetFileNameWithoutExtension(Pic);
            string Source = AbsolutePath + Pic;
            string Dest = AbsolutePath + PathToImg + "\\" + Prefix + PictureName + ".jpg";
            // Bild nur herstellen, wenn es nicht existiert
            if (!File.Exists(Dest))
            {
                System.Drawing.Image img = GetThumb(Source, PixelSize);
                if (img == null)
                {
                }
                else
                {
                    img.Save(Dest, ImageFormat.Jpeg);
                    img.Dispose();
                }
            }
        }
        public static System.Drawing.Image GetThumb(string ImagePath, int Size)
        {
            if (Size > 0)
            {
                System.Drawing.Bitmap myBitmap;
                try
                {
                    myBitmap = new System.Drawing.Bitmap(ImagePath);
                }
                catch
                {
                    // p.Response.Write("Not Found: " + ImagePath + "<br/>"); p.Response.Flush();
                    return null;
                }
                int ResolutionHorizontal;
                int ResolutionVertical;
                if (myBitmap.Width > myBitmap.Height) // Querformat
                {
                    ResolutionHorizontal = Size;
                    ResolutionVertical = (Size * myBitmap.Height) / myBitmap.Width;
                }
                else // Hochformat
                {
                    ResolutionVertical = Size;
                    ResolutionHorizontal = (Size * myBitmap.Width) / myBitmap.Height;
                }
                Bitmap bmPhoto = new Bitmap(ResolutionHorizontal, ResolutionVertical,
                                         PixelFormat.Format24bppRgb);
                bmPhoto.SetResolution(myBitmap.HorizontalResolution, myBitmap.VerticalResolution);

                Graphics grPhoto = Graphics.FromImage(bmPhoto);
                grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

                grPhoto.DrawImage(myBitmap,
                    new Rectangle(0, 0, ResolutionHorizontal, ResolutionVertical),
                    new Rectangle(0, 0, myBitmap.Width, myBitmap.Height),
                    GraphicsUnit.Pixel);
                grPhoto.Dispose();
                myBitmap.Dispose();
                return bmPhoto;
            }
            else
            {
                System.Drawing.Image myOriginal = System.Drawing.Image.FromFile(ImagePath);
                return myOriginal;
            }
        }
    }
}