using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Mediachase.Commerce.Catalog.Dto;
using System.Data;
using Mediachase.Commerce.Catalog;
using System.Collections;
using System.Collections.Specialized;
using Mediachase.Web.Console.Common;
using Mediachase.MetaDataPlus.Configurator;
using Mediachase.Web.Console.BaseClasses;
using Mediachase.Web.Console.Interfaces;
using Mediachase.Cms.Dto;
using Mediachase.Cms.Managers;
using Mediachase.Commerce.Storage;
using Mediachase.MetaDataPlus;
using Mediachase.Cms;

namespace Nansen.Commerce.Manager.Additions.Apps.Catalog.ExtensionTabs
{
    public partial class EntryOverviewEditTab : CatalogBaseUserControl, IAdminTabControl, IDynamicParamControl, IPreCommit, IAdminContextControl
    {
		protected Nansen.Commerce.Additions.Apps.Core.ExtensionMetaData.EditTab MetaDataTab;
		protected global::Mediachase.Commerce.Manager.Core.Controls.BooleanEditControl IsActive;
		protected global::Mediachase.Commerce.Manager.Core.Controls.CalendarDatePicker AvailableFrom;
		protected global::Mediachase.Commerce.Manager.Core.Controls.CalendarDatePicker ExpiresOn;

        // Fields
        private CatalogEntryDto _CatalogEntryDto;
        private const string _CatalogEntryDtoString = "CatalogEntryDto";
        private CatalogRelationDto _CatalogRelationDto;
        private const string _CatalogRelationDtoString = "CatalogRelationDto";
        private const string _MappingCatalogRelationDtoString = "MappingsCatalogRelationDto";
        private CatalogRelationDto _MappingRelationDto;


        // Methods
        private void BindForm()
        {

           
            MetaClass class2 = MetaClass.Load(CatalogContext.MetaDataContext, "CatalogEntry");
            this.MetaClassList.Items.Clear();
            if (class2 != null)
            {
                foreach (MetaClass class3 in class2.ChildClasses)
                {
                    this.MetaClassList.Items.Add(new ListItem(class3.FriendlyName, class3.Id.ToString()));
                }
                this.MetaClassList.DataBind();
            }
            TemplateDto templateDto = DictionaryManager.GetTemplateDto();
            if (templateDto.main_Templates.Count > 0)
            {
                DataView defaultView = templateDto.main_Templates.DefaultView;
                defaultView.RowFilter = "TemplateType = 'entry'";
                this.DisplayTemplate.DataSource = defaultView;
                this.DisplayTemplate.DataBind();
            }
            if (this.CatalogEntryId > 0)
            {
                if (this._CatalogEntryDto.CatalogEntry.Count > 0)
                {
                    this.Name.Text = this._CatalogEntryDto.CatalogEntry[0].Name;
                    this.AvailableFrom.Value = ManagementHelper.GetUserDateTime(this._CatalogEntryDto.CatalogEntry[0].StartDate);
                    this.ExpiresOn.Value = ManagementHelper.GetUserDateTime(this._CatalogEntryDto.CatalogEntry[0].EndDate);
                    this.CodeText.Text = this._CatalogEntryDto.CatalogEntry[0].Code;
                    this.IsActive.IsSelected = this._CatalogEntryDto.CatalogEntry[0].IsActive;
                    if (!this._CatalogEntryDto.CatalogEntry[0].IsTemplateNameNull())
                    {
                        ManagementHelper.SelectListItem(this.DisplayTemplate, this._CatalogEntryDto.CatalogEntry[0].TemplateName);
                    }
                    ManagementHelper.SelectListItem(this.MetaClassList, this._CatalogEntryDto.CatalogEntry[0].MetaClassId);
                    if (this._CatalogRelationDto.NodeEntryRelation.Count > 0)
                    {
                        this.SortOrder.Text = this._CatalogRelationDto.NodeEntryRelation[0].SortOrder.ToString();
                    }
                    else
                    {
                        this.SortOrder.Text = "-1";
                    }
                }
            }
            else
            {
                this.AvailableFrom.Value = ManagementHelper.GetUserDateTime(DateTime.UtcNow);
                this.ExpiresOn.Value = ManagementHelper.GetUserDateTime(DateTime.UtcNow).AddYears(10);
            }
        }

        private void BindLanguageDropDown()
        {
           

            CatalogDto catalogDto = null;
            if (this.CatalogEntryId == 0)
            {
                catalogDto = CatalogContext.Current.GetCatalogDto(this.ParentCatalogId);
            }
            else if (this.CatalogEntryId > 0)
            {
                CatalogEntryDto catalogEntryDto = CatalogContext.Current.GetCatalogEntryDto(this.CatalogEntryId);
                if (catalogEntryDto.CatalogEntry.Count > 0)
                {
                    catalogDto = CatalogContext.Current.GetCatalogDto(catalogEntryDto.CatalogEntry[0].CatalogId);
                }
            }

            if (catalogDto != null)
            {
                List<string> list = new List<string>();

                Dictionary<string, string> languages = new Dictionary<string, string>();

                using (IDataReader reader = Language.GetAllLanguages())
                {

                    while (reader.Read())
                    {
                        languages.Add(reader["LangName"].ToString().ToLower(), reader["FriendlyName"].ToString());
                    }
                }

                LanguageSelector.Items.Add(new ListItem(languages[catalogDto.Catalog[0].DefaultLanguage], catalogDto.Catalog[0].DefaultLanguage));



                if (catalogDto.CatalogLanguage.Count > 0)
                {
                    foreach (CatalogDto.CatalogLanguageRow row in catalogDto.CatalogLanguage.Rows)
                    {
                        LanguageSelector.Items.Add(new ListItem(languages[row.LanguageCode], row.LanguageCode));

                    }
                }
            }

        }

        private void BindMetaForm(string languagecode)
        {

            CatalogDto catalogDto = null;
            if (this.CatalogEntryId == 0)
            {
                catalogDto = CatalogContext.Current.GetCatalogDto(this.ParentCatalogId);
            }
            else if (this.CatalogEntryId > 0)
            {
                this.MetaDataTab.ObjectId = this.CatalogEntryId;
                CatalogEntryDto catalogEntryDto = CatalogContext.Current.GetCatalogEntryDto(this.CatalogEntryId);
                if (catalogEntryDto.CatalogEntry.Count > 0)
                {
                    catalogDto = CatalogContext.Current.GetCatalogDto(catalogEntryDto.CatalogEntry[0].CatalogId);
                    this.MetaDataTab.MetaClassId = catalogEntryDto.CatalogEntry[0].MetaClassId;
                }
            }
            if (!string.IsNullOrEmpty(this.MetaClassList.SelectedValue))
            {
                this.MetaDataTab.MetaClassId = int.Parse(this.MetaClassList.SelectedValue);
            }
            if (catalogDto != null)
            {
                List<string> list = new List<string>();
                if (String.IsNullOrEmpty(languagecode))
                {
                    list.Add(catalogDto.Catalog[0].DefaultLanguage);
                }
                else
                {
                    list.Add(languagecode);
                }
           
                this.MetaDataTab.EditLanguages = list.ToArray();                
            }
			if (catalogDto != null)
			{
				List<string> list = new List<string>();
				list.Add(catalogDto.Catalog[0].DefaultLanguage);
				if (catalogDto.CatalogLanguage.Count > 0)
				{
					foreach (CatalogDto.CatalogLanguageRow catalogLanguageRow in (InternalDataCollectionBase)catalogDto.CatalogLanguage.Rows)
						list.Add(catalogLanguageRow.LanguageCode);
				}
				this.MetaDataTab.Languages = list.ToArray();
				this.MetaDataTab.DataBind();
			}
            int parentCatalogNodeId = this.ParentCatalogNodeId;
        }

        private void CatalogEntry_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            CatalogEntryDto.CatalogEntryDataTable table = (CatalogEntryDto.CatalogEntryDataTable)sender;
            CatalogEntryDto.CatalogEntryRow row = (CatalogEntryDto.CatalogEntryRow)table.Rows[0];
            if (row.CatalogEntryId > 0)
            {
                this.MetaDataTab.MetaClassId = row.MetaClassId;
                this.MetaDataTab.ObjectId = row.CatalogEntryId;
            }
        }

        public void EntryCodeCheck(object sender, ServerValidateEventArgs args)
        {
            CatalogEntryDto catalogEntryDto = CatalogContext.Current.GetCatalogEntryDto(this.CodeText.Text);
            if ((catalogEntryDto.CatalogEntry.Count > 0) && (catalogEntryDto.CatalogEntry[0].CatalogEntryId != this.CatalogEntryId))
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        public void LoadContext(IDictionary context)
        {
            this._CatalogEntryDto = (CatalogEntryDto)context["CatalogEntryDto"];
            this._CatalogRelationDto = (CatalogRelationDto)context["CatalogRelationDto"];
            this._MappingRelationDto = (CatalogRelationDto)context["MappingsCatalogRelationDto"];
        }

        private void MetaClassList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindMetaForm(LanguageSelector.SelectedValue);
        }

        public void NameLengthValidator_Validate(object sender, ServerValidateEventArgs e)
        {
            CatalogEntryDto dto = new CatalogEntryDto();
            e.IsValid = this.Name.Text.Length <= dto.CatalogEntry.Columns["Name"].MaxLength;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.MetaClassList.SelectedIndexChanged += new EventHandler(this.MetaClassList_SelectedIndexChanged);
            if (!this.Page.IsPostBack)
            {
                this.BindLanguageDropDown();
                this.BindForm();
            }
            if (base.Request["__EVENTTARGET"] != this.MetaClassList.UniqueID)
            {
                this.BindMetaForm(LanguageSelector.SelectedValue);
            }

            LanguageSelector.SelectedIndexChanged += new EventHandler(LanguageSelector_SelectedIndexChanged);

        }

        void LanguageSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            var language = LanguageSelector.SelectedValue;
            BindMetaForm(language);
        }

        public void PreCommitChanges(IDictionary context)
        {
            CatalogEntryDto dto = (CatalogEntryDto)context["CatalogEntryDto"];
            CatalogRelationDto dto1 = (CatalogRelationDto)context["CatalogRelationDto"];
            CatalogRelationDto dto2 = (CatalogRelationDto)context["MappingsCatalogRelationDto"];
            IDictionary dictionary = new ListDictionary();
            this.MetaDataTab.MDContext = CatalogContext.MetaDataContext;
            this.MetaDataTab.SaveChanges(dictionary);
            byte[] binaryValue = ((MetaObjectSerialized)dictionary["MetaObjectSerialized"]).BinaryValue;
            dto.CatalogEntry[0]["SerializedData"] = binaryValue;
            foreach (CatalogRelationDto.NodeEntryRelationRow row in dto2.NodeEntryRelation)
            {
                if ((row.RowState != DataRowState.Deleted) && (row.CatalogEntryId == dto.CatalogEntry[0].CatalogEntryId))
                {
                    row.SortOrder = int.Parse(this.SortOrder.Text);
                }
            }
        }

        public void SaveChanges(IDictionary context)
        {
            CatalogEntryDto dto = (CatalogEntryDto)context["CatalogEntryDto"];
            CatalogEntryDto.CatalogEntryRow row = null;
            if ((dto.CatalogEntry == null) || (dto.CatalogEntry.Count == 0))
            {
                row = dto.CatalogEntry.NewCatalogEntryRow();
                row.ApplicationId = CatalogConfiguration.Instance.ApplicationId;
                row.ClassTypeId = this.EntryType;
            }
            else
            {
                row = dto.CatalogEntry[0];
                if (row.MetaClassId != int.Parse(this.MetaClassList.SelectedValue))
                {
                    MetaObject.Delete(CatalogContext.MetaDataContext, row.CatalogEntryId, row.MetaClassId);
                }
            }
            row.Name = this.Name.Text;
            row.StartDate = this.AvailableFrom.Value.ToUniversalTime();
            row.EndDate = this.ExpiresOn.Value.ToUniversalTime();
            row.Code = this.CodeText.Text;
            row.IsActive = this.IsActive.IsSelected;
            if ((this.ParentCatalogId > 0) && (row.RowState == DataRowState.Detached))
            {
                row.CatalogId = this.ParentCatalogId;
            }
            row.TemplateName = this.DisplayTemplate.SelectedValue;
            row.MetaClassId = int.Parse(this.MetaClassList.SelectedValue);
            if (row.RowState == DataRowState.Detached)
            {
                dto.CatalogEntry.Rows.Add(row);
            }
            dto.CatalogEntry.RowChanged += new DataRowChangeEventHandler(this.CatalogEntry_RowChanged);
        }

        // Properties
        public int CatalogEntryId
        {
            get
            {
                return ManagementHelper.GetIntFromQueryString("catalogentryid");
            }
        }

        public string EntryType
        {
            get
            {
                return base.Request.QueryString["type"];
            }
        }

        public int ParentCatalogId
        {
            get
            {
                return ManagementHelper.GetIntFromQueryString("catalogid");
            }
        }

        public int ParentCatalogNodeId
        {
            get
            {
                return ManagementHelper.GetIntFromQueryString("catalognodeid");
            }
        }

      

 

 
    
    }
}