//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.IO;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Galleries.Components;
using Telligent.CommunityServer.MetadataExtractor;
using Telligent.CommunityServer.MetadataExtractor.Imaging.Jpeg;
using Directory = Telligent.CommunityServer.MetadataExtractor.Directory;
using Tag = Telligent.CommunityServer.MetadataExtractor.Tag;

namespace CommunityServer.Galleries.Controls
{

    public class ExifListing : GalleryThemedControl
    {

        #region Child Controls

        private Repeater ExifProperties;
        private HyperLink ExifLink;

        #endregion

        #region Public Properties

        private GalleryPost dataSource = null;
        public GalleryPost DataSource
        {
            get { return dataSource; }
            set { dataSource = value; }
        }

        private bool showAll = false;
        /// <summary>
        /// Setting this to true overides the default exif list set for the gallery
        /// </summary>
        public bool ShowAll
        {
            get { return showAll; }
            set { showAll = value; }
        }

        private bool showNoExifMessage = false;
        /// <summary>
        /// Causes the control to render even when there are no Exif properties 
        /// (usually used with the RepeaterPlusNone in the skin)
        /// </summary>
        public bool ShowNoExifMessage
        {
            get { return showNoExifMessage; }
            set { showNoExifMessage = value; }
        }

        #endregion

        #region Skin

        protected override void AttachChildControls()
        {
            ExifProperties = (Repeater)FindControl("ExifProperties");
            ExifLink = (HyperLink)FindControl("ExifLink");

            InitializeChildControls();
        }

        private void InitializeChildControls()
        {
            if (ExifProperties != null)
                ExifProperties.ItemDataBound += new RepeaterItemEventHandler(ExifProperties_ItemDataBound);
        }

        #endregion

        #region Event Overrides

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.DataBind();
        }

        public override void DataBind()
        {
            base.DataBind();
            BindData();
        }

        #endregion

        private void BindData()
        {
            CSContext cSContext = CSContext.Current;
            if (DataSource == null)
                DataSource = GalleryPosts.GetPicture(cSContext.PostID);
            BindExifProperties();

            if (ExifLink != null)
            {
                if (cSContext.CategoryID > 0)
                    ExifLink.NavigateUrl = GalleryUrls.Instance().ViewExif(this.CurrentGallery.ApplicationKey, cSContext.CategoryID, DataSource);
                else
                    ExifLink.NavigateUrl = GalleryUrls.Instance().ViewExif(this.CurrentGallery.ApplicationKey, DataSource);

                ExifLink.Text = ResourceManager.GetString("Gallery_ExifListing_More");
            }
        }

        private void BindExifProperties()
        {
            if (!DataSource.EnableExif)
            {
                this.Visible = false;
                return;
            }

            // Set the data source for the EXIF properties
            if (ExifProperties != null)
            {
                Metadata metadata = GalleryPosts.GetPictureMetadata(DataSource.PostID);
                ArrayList displayProperties = new ArrayList();

                if (metadata.GetDirectoryCount() == 0)
                {
                    PostAttachment pictureData = GalleryPosts.GetPictureData(DataSource);

                    // Check to make sure it is a valid image
                    ImageInfo imageInfo = new ImageInfo(pictureData.Content);
                    if (DataSource.IsPicture && imageInfo.Check())
                    {
                        if (imageInfo.Format == ImageInfo.FORMAT_JPEG)
                        {
							pictureData.Content.Position = 0;
                            metadata = JpegMetadataReader.ReadMetadata(pictureData.Content);
                            GalleryPosts.UpdatePictureMetadata(DataSource.PostID, metadata);
                        }
                    }
                }

                if (ShowAll)
                {
                    foreach (Directory directory in metadata.DirectoryList)
                    {
                        IEnumerator tagsIterator = directory.GetTagIterator();

                        while (tagsIterator.MoveNext())
                        {
                            Tag tag = (Tag)tagsIterator.Current;
                            displayProperties.Add(tag);
                        }
                    }
                    displayProperties.Sort();
                }
                else
                {
                    string[] properties = CurrentGallery.DisplayExifProperties;
                    Hashtable showProperties = new Hashtable();

                    foreach (string prop in properties)
                        showProperties.Add(prop, true);

                    foreach (Directory directory in metadata.DirectoryList)
                    {
                        IEnumerator tagsIterator = directory.GetTagIterator();
                        while (tagsIterator.MoveNext())
                        {
                            Tag tag = (Tag)tagsIterator.Current;
                            if (showProperties.Contains(directory.GetType().FullName + ":" + tag.GetTagType()))
                                displayProperties.Add(tag);
                        }
                    }
                }

                if (displayProperties.Count == 0 && !ShowNoExifMessage)
                    this.Visible = false;
                else
                {
                    ExifProperties.DataSource = displayProperties;
                    ExifProperties.DataBind();
                }
            }
        }


        private void ExifProperties_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Tag dataItem = (Tag)e.Item.DataItem;

            switch (e.Item.ItemType)
            {
                case ListItemType.Item:
                case ListItemType.AlternatingItem:

					try
					{
						Literal name = (Literal)e.Item.FindControl("PropertyName");
						if (name != null)
							name.Text = dataItem.GetTagName();

						Literal val = (Literal)e.Item.FindControl("PropertyValue");
						if (val != null)
							val.Text = dataItem.GetDescription();
					}
            		catch
            		{
						e.Item.Visible = false;
            		}

                    break;
            }
        }
    }
}