using System;
using System.Collections.Generic;
using System.Web.UI;
using Bitrix;

using Bitrix.Components;
using Bitrix.DataLayer;
using Bitrix.IBlock;
using Bitrix.UI;
using Bitrix.DataTypes;
using Bitrix.IO;
using Bitrix.Services;
using Bitrix.Configuration;

public partial class PhotogalleryAlbum : BXComponent
{
    //PROPERTIES
    public BXInfoBlockSectionOld Album
    {
        get
        {
            return BXInfoBlockSectionManagerOld.ConvertToOldElement(Results.Get<BXIBlockSection>("CurrentAlbum", null));
        }
    }

    public BXIBlockSection AlbumItem
    {
        get
        {
            return Results.Get<BXIBlockSection>("CurrentAlbum", null);
        }
        set
        {
            Results["CurrentAlbum"] = value;
        }
    }

    public int AlbumId
    {
        #region old
        //get
        //{
        //    if (!IsComponentDesignMode)
        //    {
        //        return Results.Get("AlbumId", 0);
        //    }
        //    return 0;
        //}
        #endregion
        get 
        {
            return Parameters.Get<int>("AlbumID", 0);
        }
    }

    public int IBlockId
    {
        get
        {
            return Parameters.Get("IBlockId", 0);
        }
    }

    public int ParentAlbumId
    {
        get
        {
            return Results.Get("ParentAlbumId", 0);
        }
        set
        {
            Results["ParentAlbumId"] = value;
        }
    }

    public string BackUrl
    {
        get { return Results.Get("BackUrl", ""); }
        set { Results["backUrl"] = value; }
    }

    public string UploadUrl
    {
        get { return Results.Get("UploadUrl", ""); }
        set { Results["UploadUrl"] = value; }
    }

    public string EditUrl
    {
        get { return Results.Get("EditUrl", ""); }
        set { Results["EditUrl"] = value; }
    }

    public string AddUrl
    {
        get { return Results.Get("AddUrl", ""); }
        set { Results["AddUrl"] = value; }
    }

    public bool IsParent
    {
        get { return Results.Get("IsParent", false); }
        set { Results["IsParent"] = value; }
    }

    public bool CanModify
    {
        get { return Results.Get("CanModify", false); }
        set { Results["CanModify"] = value; }
    }

    public bool IsNested
    {
        get { return Results.Get("IsNested", false); }
        set { Results["IsNested"] = value; }
    }

    public string AlbumCoverUrl
    {
        get { return Results.Get("AlbumCoverUrl", ""); }
        set { Results["AlbumCoverUrl"] = value; }
    }

    BXInfoBlockElementCollectionOld photos;

    public BXInfoBlockElementCollectionOld Photos
    {
        get
        {
            return photos ?? (photos = BXInfoBlockElementManagerOld.ConvertToOldElements(Results.Get("Photos", new BXIBlockElementCollection())));
        }
    }

    public BXIBlockElementCollection PhotoItems
    {
        get
        {
            return Results.Get("Photos", new BXIBlockElementCollection());
        }
        set
        {
            Results["Photos"] = value;
        }
    }

    BXInfoBlockSectionCollectionOld _sections = null;
    BXInfoBlockElementCollectionOld _photoDescription = null;

    public BXInfoBlockSectionCollectionOld Sections
    {
        get 
        {
            /*
            if (_sections != null)
                return _sections;
            _sections = BXInfoBlockSectionManagerOld.ConvertToOldElements(Results.Get("Sections", new BXIBlockSectionCollection()));
            return _sections;
            */
            return _sections ?? (_sections = BXInfoBlockSectionManagerOld.ConvertToOldElements(Results.Get("Sections", new BXIBlockSectionCollection())));

        }
    }

    protected BXInfoBlockSectionOld GetSectionOldById(int id)
    {
        foreach (BXInfoBlockSectionOld s in Sections)
            if (s.SectionId == id)
                return s;
        return null;
    }

    protected BXInfoBlockElementOld GetElementOldById(int id)
    {
        foreach (BXInfoBlockElementOld item in Photos)
            if (item.ElementId == id) return item;
       
        return null;   
        
    }


    public BXIBlockSectionCollection SectionItems
    {
        get { return Results.Get("Sections", new BXIBlockSectionCollection()); }
        set { Results["Sections"] = value; }
    } 


    public int PreviewHeight
    {
        get
        {
            return Parameters.Get("PreviewHeight", 75);
        }
    }

    public int PreviewWidth
    {
        get
        {
            return Parameters.Get("PreviewWidth", 75);
        }
    }

    public Dictionary<BXInfoBlockSectionOld, AlbumDescription> AlbumDescription
    {
        get
        {
            return ConvertToOldAlbumDescription();
        }
    }

    public Dictionary<BXIBlockSection, AlbumDescription> AlbumDescriptionDictionary
    {
        get
        {
            return Results.Get("AlbumDescription", new Dictionary<BXIBlockSection, AlbumDescription>());
        }
        set
        {
            Results["AlbumDescription"] = value;
        }
    }
    Dictionary<BXInfoBlockElementOld, PhotoDescription> _photoDescriptionDic;


    public Dictionary<BXInfoBlockElementOld, PhotoDescription> PhotoDescription
    {
        get
        {
            return _photoDescriptionDic ?? (_photoDescriptionDic = GetOldPhotoDescription());
        }
    }

    Dictionary<BXIBlockElement, PhotoDescription> _photoDescriptionDictionary;

    public Dictionary<BXIBlockElement, PhotoDescription> PhotoDescriptionDictionary
    {
        get
        {
            return _photoDescriptionDictionary ?? (_photoDescriptionDictionary = Results.Get("PhotoDescription", new Dictionary<BXIBlockElement, PhotoDescription>()));
        }
        set
        {
            Results["PhotoDescription"] = value;
        }
    }

    public string errorMessage = String.Empty;

    //METHODS
    protected void Page_Load(object sender, EventArgs e)
    {
		if (IBlockId > 0)
		{
			//if (EnableSef)
			//{
			//	MapVariable(Parameters.Get<string>("SEFFolder", "/photogallery"), Parameters.Get<string>("SEF_Album"), Results);
			//}
            //else
            //{
            //    BXParamsBag<string> variableAlias = new BXParamsBag<string>();
            //    variableAlias["AlbumID"] = Parameters.Get<string>("ParamAlbum", "Album");
            //    variableAlias["PageID"] = Parameters.Get<string>("ParamAlbumPage", "Album");
            //    variableAlias["PageShowAll"] = Parameters.Get<string>("ParamAlbumShowAll", "Album");
            //    MapVariable(variableAlias, Results);

            //    if (AlbumId > 0)
            //    {
            //        Results["AlbumParentID"] = BXInfoBlockSectionManagerOld.GetById(AlbumId).ParentSectionId;
            //    }
            //}

			int albumParent = 0;

			if (BXIBlock.GetById(IBlockId).IsUserCanOperate("IBlockModifyStructure"))
				CanModify = true;

			if (AlbumId > 0)
			{
				//load album
				AlbumItem = BXIBlockSection.GetById(AlbumId,Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);

                if (AlbumItem != null)
                {
                    albumParent = AlbumItem.SectionId;



                    if (Page is BXPublicPage)
                        ((BXPublicPage)Page).MasterTitle = Server.HtmlDecode(AlbumItem.Name);
                    Page.Title = AlbumItem.Name;
                    IsNested = true;

                    BXFile image = AlbumItem.Image;

                    if (image != null)
                    {
                        Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
                               BXImageUtility.GetResizedImage(image, Parameters.Get("PreviewWidth", 75),
                               Parameters.Get("PreviewHeight", 75));

                        AlbumCoverUrl = BXPath.ToUri(imageInfo.FilePath, true);
                        /*string.Format(
						"{0}ImageResizer.ashx?path={1}&width={2}&height={3}&fit=true",
						BXUri.ToRelativeUri("~/bitrix/handlers/Main/"),
						UrlEncode(image.FileVirtualPath),
						Parameters.Get("CoverWidth", 75),
						Parameters.Get("CoverHeight", 75));*/
                    }

                    FillNavChain();
                }
			}

			BackUrl = GetAlbumUrl(albumParent);

			UploadUrl = MakeLink(Parameters.Get<string>("UrlTemplateUpload", BXConfigurationUtility.Constants.ErrorHref), AlbumId);
			EditUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumEdit", BXConfigurationUtility.Constants.ErrorHref), AlbumId);
			AddUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumEdit", BXConfigurationUtility.Constants.ErrorHref), 0);

			BXFilter filter = new BXFilter();

			if (AlbumItem != null)
			{

				filter.Add(new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal,Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.SectionId, BXSqlFilterOperators.Equal,AlbumItem.Id));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel,BXSqlFilterOperators.Less,Album.DepthLevel + 2));

				BXFilter photoFilter = new BXFilter();
				photoFilter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				photoFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal,Album.SectionId));

				BXParamsBag<object> mapParams = new BXParamsBag<object>();
                BXPagingParams pagingParams = new BXPagingParams();
				mapParams["AlbumID"] = AlbumId;
                pagingParams.AllowPaging = true;
                pagingParams.Page = Parameters.Get<int>("PageID");
				mapParams["PageID"] = Parameters.Get<string>("PageID");
                //Идеологически неверно PageID уже должен быть в параметрах
                //mapParams["PageID"] = Results.Get<string>("PageID");
                pagingParams.ShowAll= Parameters.Get<bool>("PageShowAll");
                pagingParams.RecordsPerPage = Parameters.Get<int>("PagingRecordsPerPage",10);
				mapParams["PageShowAll"] = Parameters.Get<string>("PageShowAll");

				BXQueryParams queryParams = PreparePaging(
					pagingParams,
                                        delegate
                                        {
                                            return BXIBlockElement.Count(photoFilter);
                                        },
                    mapParams,
					"PageID",
					Parameters.Get<string>("UrlTemplateAlbum"),
					Parameters.Get<string>("UrlTemplateAlbumPage"),
					Parameters.Get<string>("UrlTemplateAlbumShowAll")
					);

				PhotoItems = BXIBlockElement.GetList(photoFilter, null, null, queryParams,Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);
				PhotoDescriptionDictionary = new Dictionary<BXIBlockElement, PhotoDescription>();

				if (Photos.Count > 0)
				{
					foreach (BXIBlockElement photo in PhotoItems)
					{
						PhotoDescription photoDesc = new PhotoDescription();

						photoDesc.Preview = string.Empty;

						BXFile image = photo.DetailImageId > 0 ? photo.DetailImage : photo.PreviewImage;

						if (image == null)
							continue;

                        Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
                        BXImageUtility.GetResizedImage(image, Parameters.Get("PreviewWidth", 150),
                        Parameters.Get("PreviewHeight", 150));

						photoDesc.Preview  = BXPath.ToUri(imageInfo.FilePath, true);
                        /*
                        = string.Format(
							"{0}ImageResizer.ashx?path={1}&width={2}&height={3}&fit={4}",
							BXUri.ToRelativeUri("~/bitrix/handlers/Main/"),
							UrlEncode(image.FileVirtualPath),
							Parameters.Get("PreviewWidth", 150),
							Parameters.Get("PreviewHeight", 150),
							!Parameters.Get("FlickrMode", false));*/

						if (!EnableSef)
						{
							photoDesc.PhotoUrl =
								string.Format("?{0}={1}", Parameters.Get<string>("ParamPhoto", "photo"), photo.Id);
						}
						else
						{
							photoDesc.PhotoUrl =
								MakeLink(Parameters.Get<string>("SEFFolder"), Parameters.Get<string>("SEF_Photo"), photo.Id);
						}

						PhotoDescriptionDictionary[photo] = photoDesc;
					}
				}

				ParentAlbumId = Album.ParentSectionId;
			}
			else
			{
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.IBlock.ID,BXSqlFilterOperators.Equal,Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel,BXSqlFilterOperators.Less, 2));
				if (Page is BXPublicPage)
					((BXPublicPage)Page).MasterTitle = GetMessageRaw("Photogallery");
				Page.Title = GetMessageRaw("Photogallery");
				ParentAlbumId = 0;
			}

			SectionItems = BXIBlockSection.GetList(filter, null,null,null,Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);
			AlbumDescriptionDictionary = new Dictionary<BXIBlockSection, AlbumDescription>();

			if ((Sections.Count != 0) && (AlbumId > 0))
				IsParent = true;

			foreach (BXIBlockSection section in SectionItems)
			{
				AlbumDescription albumDesc = new AlbumDescription();

				filter = new BXFilter();
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal,section.Id));

				BXIBlockElementCollection elements = BXIBlockElement.GetList(filter, null);

				albumDesc.CoverImageUrl =
					BXUri.ToRelativeUri(
						"~/bitrix/components/bitrix/photogallery.album/templates/.default/images/no_image.png");

				albumDesc.Count = elements.Count;

				albumDesc.Url = GetAlbumUrl(section.Id);
				albumDesc.EditUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumEdit", BXConfigurationUtility.Constants.ErrorHref), section.Id);

				BXFile image = section.Image;

				if (image == null)
					foreach (BXIBlockElement element in elements)
					{
						image = element.PreviewImage;
						if (image != null)
							break;
					}


				if (image != null)
				{

                    if (System.IO.File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(image.FilePath)))
                    {
                        Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
                            BXImageUtility.GetResizedImage(image, Parameters.Get("CoverWidth", 75),
                            Parameters.Get("CoverHeight", 75));
                    

                        if(imageInfo.FilePath!=String.Empty)

                        albumDesc.CoverImageUrl = BXPath.ToUri(imageInfo.FilePath, true);
                             /*string.Format(
                            "{0}ImageResizer.ashx?path={1}&width={2}&height={3}&fit=false",
                            BXUri.ToRelativeUri("~/bitrix/handlers/Main/"),
                            UrlEncode(image.FileVirtualPath),
                            Parameters.Get("CoverWidth", 75),
                            Parameters.Get("CoverHeight", 75));*/
                    }

				}

				AlbumDescriptionDictionary[section] = albumDesc;
                
			}

		}

        IncludeComponentTemplate();
    }

    private void FillNavChain()
    {
        BXMenu menu = BXMenuManager.Load(Request.AppRelativeCurrentExecutionFilePath, "left");

        BXIBlockSectionCollection navChain = BXIBlockSection.GetNavChain(AlbumId);

        for (int i = 0; i < navChain.Count; i++)
        {
            string albumUrl =
                MakeLink(Parameters.Get<string>("UrlTemplateAlbum", BXConfigurationUtility.Constants.ErrorHref), navChain[i].SectionId);

            string parentAlbumUrl;

            if (i != 0)
            {
                parentAlbumUrl =
                    MakeLink(Parameters.Get<string>("UrlTemplateAlbum", BXConfigurationUtility.Constants.ErrorHref), navChain[i].SectionId);
            }
            else
            {
                parentAlbumUrl = Parameters.Get<string>("GalleryRoot");
            }

            BXSiteMapManager.AddNode(
                parentAlbumUrl,
                albumUrl,
                navChain[i].Name);
        }
    }

    public override bool ProcessCommand(string commandName, BXParamsBag<object> commandParameters,List<string> commandErrors)
    {
        int parentAlbumId=0;
        try
        {
            parentAlbumId = BXIBlockSection.GetById(AlbumId).SectionId;
            BXIBlockSection.Delete(AlbumId);
        }
        catch (Exception ex)
        {
            errorMessage = GetMessage("Error.FailedToDeleteAlbum");
        }
        string url;
        if (EnableSef)
        {
            if (parentAlbumId > 0)
            {
                Results["AlbumId"] = parentAlbumId;
                url = MakeLink(Parameters.Get<string>("SefFolder"), Parameters.Get<string>("Sef_Album"), Results);
            }
            else
            {
                url = MakeLink(Parameters.Get<string>("SefFolder"), string.Empty, Results);
            }
        }
        else
        {
            if (parentAlbumId > 0)
            {
                url = string.Format("{0}?{1}={2}",
                                    Request.Path,
                                    Parameters.Get<string>("ParamAlbum", "Album"),
                                    parentAlbumId);
            }
            else
            {
                url = Request.Path;
            }
        }
        if (errorMessage == String.Empty)
        {
            if (Parameters.Get("EnableAjax", false) && !IsComponentDesignMode)
            {
                string script = string.Format("setTimeout(\"PageTransfer('{0}');\",1);",
                                              url);
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "AJAX_BUTTON_CLICK", script, true);
            }
            else
                Response.Redirect(url);
            return true;
        }
        else return false;

        
    }

    protected override void PreLoadComponentDefinition()
    {
		Title = GetMessage("PhotogalleryAlbum.Title");
		Description = GetMessage("PhotogalleryAlbum.Description");
		Icon = "images/icon.gif";
		
		ParamsDefinition.Add(BXParametersDefinition.Paging);
    }

    protected string GetAlbumUrl(int albumId)
    {
        if (albumId == 0)
            return Parameters.Get<string>("GalleryRoot", Request.Path);
        else
            return MakeLink(Parameters.Get<string>("UrlTemplateAlbum", BXConfigurationUtility.Constants.ErrorHref), albumId);
    }

    public Dictionary<BXInfoBlockSectionOld, AlbumDescription> ConvertToOldAlbumDescription()
    {
        Dictionary<BXInfoBlockSectionOld, AlbumDescription> result = new Dictionary<BXInfoBlockSectionOld,AlbumDescription>();
        foreach (BXIBlockSection item in AlbumDescriptionDictionary.Keys)
        {

            result.Add(GetSectionOldById(item.Id), AlbumDescriptionDictionary[item]);
        }
        return result;
    }



    protected Dictionary<BXInfoBlockElementOld, PhotoDescription> GetOldPhotoDescription()
    {


            Dictionary<BXInfoBlockElementOld, PhotoDescription> result = new Dictionary<BXInfoBlockElementOld, PhotoDescription>();
            foreach (BXIBlockElement item in PhotoDescriptionDictionary.Keys)
            {
                result.Add(GetElementOldById(item.Id), PhotoDescriptionDictionary[item]);
            }
            return result;
        
    }
}



public class AlbumDescription
{
    public string Url;
    public string EditUrl;
    public string CoverImageUrl;
    public int Count;
}

public class PhotoDescription
{
    public string Preview;
    public string PhotoUrl;
}