using System;
using System.Collections.Generic;
using System.Web;

using Bitrix.Components;
using Bitrix.DataLayer;
using Bitrix.IBlock;
using Bitrix.Modules;
using Bitrix.Services;
using Bitrix.UI;
using Bitrix.DataTypes;
using Bitrix.Components.Editor;

public partial class PhotoGallery : BXComponent
{

    const int DefaultPreviewWidth = 75;
    const int DefaultPreviewHeight = 75;
    const int DefaultPhotoWidth = 150;
    const int DefaultPhotoHeight = 150;

    protected void Page_Load(object sender, EventArgs e)
    {
        BXParamsBag<string> urlToPage = UrlToPageSetUp();

        string page;

        if (EnableSef)
        {
            page = Map(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage, "album");
            MapVariable(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage, Results);

            if (page == "album.page")
                page = "album";
            else if (page == "album.showall")
            {
                page = "album";
                Results["PageShowAll"] = true;
            }

            Results["GalleryRoot"] = MakeLink(Parameters.Get<string>("SEFFolder", "/photogallery"), "");
        }
        else
        {
            page = Map(urlToPage, "album");

            BXParamsBag<string> variableAlias = new BXParamsBag<string>();
            switch (page)
            {
                case "album":
                    variableAlias["AlbumID"] = Parameters.Get<string>("ParamAlbum", "Album");
                    variableAlias["PageID"] = Parameters.Get<string>("ParamAlbumPage", "Album");
                    variableAlias["PageShowAll"] = Parameters.Get<string>("ParamAlbumShowAll", "Album");
                    break;
                case "album.edit":
                    variableAlias["AlbumID"] = Parameters.Get<string>("ParamAlbumEdit", "AlbumEdit");
                    break;
                case "photo":
                    variableAlias["PhotoId"] = Parameters.Get<string>("ParamPhoto", "photo");
                    break;
                case "photo.edit":
                    variableAlias["PhotoId"] = Parameters.Get<string>("ParamPhotoEdit", "photoedit");
                    break;
                case "upload":
                    variableAlias["AlbumID"] = Parameters.Get<string>("ParamAlbumUpload", "AlbumUpload");
                    break;
            }

            MapVariable(variableAlias, Results);

            if (Results.ContainsKey("AlbumID"))
            {
                int id = Results.Get<int>("AlbumId", 0);
                if (id > 0)
                {
                    BXIBlockSection parent = BXIBlockSection.GetById(Results.Get("AlbumId", 0));

                    Results["AlbumParentID"] = (parent!=null)? parent.SectionId:0;

                }

            }
            Results["GalleryRoot"] = BXSefUrlManager.CurrentUrl.AbsolutePath;
        }
        Results["PageShowAll"] = Results.ContainsKey("PageShowAll");


        UrlTemplateSetUp(urlToPage);


        IncludeComponentTemplate(page);
    }

    private void UrlTemplateSetUp(BXParamsBag<string> urlToPage)
    {
        if (EnableSef)
        {
            Results["UrlTemplateAlbum"] = CombineLink(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage["album"]);
            Results["UrlTemplateAlbumPage"] = CombineLink(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage["album.page"]);
            Results["UrlTemplateAlbumShowAll"] = CombineLink(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage["album.showall"]);
            Results["UrlTemplateAlbumEdit"] = CombineLink(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage["album.edit"]);
            Results["UrlTemplatePhoto"] = CombineLink(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage["photo"]);
            Results["UrlTemplatePhotoEdit"] = CombineLink(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage["photo.edit"]);
            Results["UrlTemplateUpload"] = CombineLink(Parameters.Get<string>("SEFFolder", "/photogallery"), urlToPage["upload"]);
        }
        else
        {
            string path = BXSefUrlManager.CurrentUrl.AbsolutePath;

            Results["UrlTemplateAlbum"] = string.Format("{0}?{1}=#AlbumId#", path, urlToPage["album"]);
            Results["UrlTemplateAlbumPage"] = string.Format("{0}?{1}=#AlbumId#&{2}=#PageId#", path, urlToPage["album"], Parameters.Get<string>("ParamAlbumPage", "Page"));
            Results["UrlTemplateAlbumShowAll"] = string.Format("{0}?{1}=#AlbumId#&{2}=", path, urlToPage["album"], Parameters.Get<string>("ParamAlbumShowAll", "Page"));
            Results["UrlTemplateAlbumEdit"] = string.Format("{0}?{1}=#AlbumId#", path, urlToPage["album.edit"]);
            Results["UrlTemplatePhoto"] = string.Format("{0}?{1}=#PhotoId#", path, urlToPage["photo"]);
            Results["UrlTemplatePhotoEdit"] = string.Format("{0}?{1}=#PhotoId#", path, urlToPage["photo.edit"]);
            Results["UrlTemplateUpload"] = string.Format("{0}?{1}=#AlbumId#", path, urlToPage["upload"]);
        }
    }

    private BXParamsBag<string> UrlToPageSetUp()
    {
        BXParamsBag<string> urlToPage = new BXParamsBag<string>();

        if (EnableSef)
        {
            urlToPage["album.edit"] = Parameters.Get<string>("SEF_AlbumEdit");
            urlToPage["upload"] = Parameters.Get<string>("SEF_Upload");
            urlToPage["album"] = Parameters.Get<string>("SEF_Album");
            urlToPage["album.page"] = Parameters.Get<string>("SEF_AlbumPage");
            urlToPage["album.showall"] = Parameters.Get<string>("SEF_AlbumShowAll");
            urlToPage["photo.edit"] = Parameters.Get<string>("SEF_PhotoEdit");
            urlToPage["photo"] = Parameters.Get<string>("SEF_Photo", "/photo/#PHOTOID#");
            urlToPage["search"] = "/search?q=#QUERY#";
        }
        else
        {
            urlToPage["album.edit"] = Parameters.Get<string>("ParamAlbumEdit", "AlbumEdit");
            urlToPage["album"] = Parameters.Get<string>("ParamAlbum", "Album");
            urlToPage["upload"] = Parameters.Get<string>("ParamAlbumUpload", "Upload");
            urlToPage["photo"] = Parameters.Get<string>("ParamPhoto", "Photo");
            urlToPage["photo.edit"] = Parameters.Get<string>("ParamPhotoEdit", "PhotoEdit");
            urlToPage["search"] = Parameters.Get<string>("ParamSearch", "Search");
        }

        return urlToPage;
    }

    protected override void PreLoadComponentDefinition()
    {
        Title = GetMessage("Title");
        Description = GetMessage("Description");
        Icon = "images/photo.gif";

        ParamsDefinition.Add(BXParametersDefinition.Paging);
        ParamsDefinition.Add(BXParametersDefinition.Search);
        ParamsDefinition.Add(BXParametersDefinition.Cache);
        //ParamsDefinition.Add(BXParametersDefinition.Sef);
        BXParamsBag<BXParam> sefParBag = BXParametersDefinition.Sef;
        string clientSideActionGroupViewId = ClientID;
        //sefParBag["EnableSEF"].ClientSideAction = new ParamClientSideActionShowSefRelated(true);
        sefParBag["EnableSEF"].ClientSideAction = new ParamClientSideActionGroupViewSwitch(clientSideActionGroupViewId, "EnableSEF", "Sef", "NonSef");
        //sefParBag["SEFFolder"].ClientSideAction = new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef);
        sefParBag["SEFFolder"].ClientSideAction = new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEFFolder", new string[] { "Sef" });
        ParamsDefinition.Add(sefParBag);

        Group = new BXComponentGroup("photo", GetMessage("Group"), 100, BXComponentGroup.Content);

        ParamsDefinition.Add(
            "IBlockTypeId",
            new BXParamSingleSelection(
                GetMessageRaw("InfoBlockType"),
                String.Empty,
                BXCategory.Main
            )
        );
        ParamsDefinition["IBlockTypeId"].RefreshOnDirty = true;


        ParamsDefinition.Add(
            "IBlockId",
            new BXParamSingleSelection(
                GetMessageRaw("InfoBlockCode"),
                String.Empty,
                BXCategory.Main
            )
        );
        ParamsDefinition["IBlockId"].RefreshOnDirty = true;


        //Управление адресами страниц
        ParamsDefinition.Add(
            "SEF_Album",
            new BXParamText(
                GetMessageRaw("BrowseAlbum.FriendlyUrl"),
                "/album/#ALBUMID#/",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEF_Album", new string[] { "Sef" }) 
            )
        );

        ParamsDefinition.Add(
            "SEF_AlbumEdit",
            new BXParamText(
                GetMessageRaw("ModifyAlbum.FriendlyUrl"),
                "/album/edit/#ALBUMID#",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEF_AlbumEdit", new string[] { "Sef" }) 
            )
        );

        ParamsDefinition.Add(
            "SEF_Upload",
            new BXParamText(
                GetMessageRaw("UploadPhotos.FriendlyUrl"),
                "/album/upload/#ALBUMID#",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEF_Upload", new string[] { "Sef" }) 
            )
        );

        ParamsDefinition.Add(
           "SEF_AlbumPage",
           new BXParamText(
               GetMessageRaw("AlbumPage.FriendlyUrl"),
               "/album/#ALBUMID#/#PAGEID#",
               BXCategory.Sef,
               //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef)
               new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEF_AlbumPage", new string[] { "Sef" }) 
           )
       );

        ParamsDefinition.Add(
           "SEF_AlbumShowAll",
           new BXParamText(
               GetMessageRaw("AlbumShowAll.FriendlyUrl"),
               "/album/#ALBUMID#/all",
               BXCategory.Sef,
               //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef)
               new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEF_AlbumShowAll", new string[] { "Sef" }) 
           )
       );

        ParamsDefinition.Add(
           "SEF_PhotoEdit",
           new BXParamText(
               GetMessageRaw("ModifyPhoto.FriendlyUrl"),
               "/photo/edit/#PHOTOID#",
               BXCategory.Sef,
               //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef)
               new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEF_PhotoEdit", new string[] { "Sef" }) 
           )
       );

        ParamsDefinition.Add(
           "SEF_Photo",
           new BXParamText(
               GetMessageRaw("BrowsePhoto.FriendlyUrl"),
               "/photo/#PHOTOID#",
               BXCategory.Sef,
               //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.Sef)
               new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "SEF_Photo", new string[] { "Sef" }) 
           )
       );


        ParamsDefinition.Add(
            "ParamAlbum",
            new BXParamText(
                GetMessageRaw("QueryParam.Album"),
                "album",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamAlbum", new string[] { "NonSef" }) 
            )
        );

        ParamsDefinition.Add(
            "ParamAlbumPage",
            new BXParamText(
                GetMessageRaw("QueryParam.AlbumPage"),
                "page",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamAlbumPage", new string[] { "NonSef" }) 
            )
        );

        ParamsDefinition.Add(
            "ParamAlbumShowAll",
            new BXParamText(
                GetMessageRaw("QueryParam.ShowAll"),
                "showall",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamAlbumShowAll", new string[] { "NonSef" }) 
            )
        );

        ParamsDefinition.Add(
            "ParamAlbumEdit",
            new BXParamText(
                GetMessageRaw("QueryParam.ModifyAlbum"),
                "AlbumEdit",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamAlbumEdit", new string[] { "NonSef" }) 
            )
        );

        ParamsDefinition.Add(
            "ParamPhoto",
            new BXParamText(
                GetMessageRaw("QueryParam.Photo"),
                "photo",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamPhoto", new string[] { "NonSef" }) 
            )
        );

        ParamsDefinition.Add(
            "ParamPhotoEdit",
            new BXParamText(
                GetMessageRaw("QueryParam.ModifyPhoto"),
                "PhotoEdit",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamPhotoEdit", new string[] { "NonSef" }) 
            )
        );

        ParamsDefinition.Add(
            "ParamSearch",
            new BXParamText(
                GetMessageRaw("QueryParam.Search"),
                "SEARCH",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamSearch", new string[] { "NonSef" }) 
            )
        );

        ParamsDefinition.Add(
            "ParamUpload",
            new BXParamText(
                GetMessageRaw("QueryParam.UploadPhotos"),
                "Upload",
                BXCategory.Sef,
                //new ParamClientSideActionShowSefRelated(ParamClientSideActionShowSefRelatedParticipantType.NonSef)
                new ParamClientSideActionGroupViewMember(clientSideActionGroupViewId, "ParamUpload", new string[] { "NonSef" }) 
            )
        );

        //Настройки фотогалереи
        ParamsDefinition.Add(
            "CoverWidth",
            new BXParamText(
                GetMessageRaw("AlbumThumbnail.WidthInPixels"),
                "75",
                BXCategory.PhotogallerySettings
            )
        );

        ParamsDefinition.Add(
            "CoverHeight",
            new BXParamText(
                GetMessageRaw("AlbumThumbnail.HeightInPixels"),
                "75",
                BXCategory.PhotogallerySettings
            )
        );

        ParamsDefinition.Add(
            "PreviewWidth",
            new BXParamText(
                GetMessageRaw("PhotoThumbnail.WidthInPixels"),
                "150",
                BXCategory.PhotogallerySettings
            )
        );

        ParamsDefinition.Add(
            "PreviewHeight",
            new BXParamText(
                GetMessageRaw("PhotoThumbnail.HeightInPixels"),
                "150",
                BXCategory.PhotogallerySettings
            )
        );

        ParamsDefinition.Add(
            "PhotoWidth",
            new BXParamText(
                GetMessageRaw("Photo.WidthInPixels"),
                "150",
                BXCategory.PhotogallerySettings
            )
        );

        ParamsDefinition.Add(
            "PhotoHeight",
            new BXParamText(
                GetMessageRaw("Photo.HeightInPixels"),
                "150",
                BXCategory.PhotogallerySettings
            )
        );

        ParamsDefinition.Add(
            "FlickrMode",
            new BXParamYesNo(
                GetMessageRaw("FlickrModeOrEnablePhotoCutting"),
                false,
                BXCategory.PhotogallerySettings
            )
        );

    }

    protected override void LoadComponentDefinition()
    {
        //ТИП ИНФОБЛОКА
        List<BXParamValue> types = new List<BXParamValue>();
        types.Add(new BXParamValue("-", ""));
        BXIBlockTypeCollection typeCollection = BXIBlockType.GetList(null,new BXOrderBy(new BXOrderByPair(BXIBlockType.Fields.Sort,BXOrderByDirection.Asc)));
        foreach (BXIBlockType t in typeCollection)
            types.Add(new BXParamValue(t.Translations[BXLoc.CurrentLocale].Name, t.Id.ToString()));
            //types.Add(new BXParamValue(t.TypeLang[BXLoc.CurrentLocale].Name, t.Id.ToString()));

        ParamsDefinition["IBlockTypeId"].Values = types;

        BXFilter iblockFilter = new BXFilter();
        if (Parameters.ContainsKey("IBlockTypeId"))
        {
            int typeId = Parameters.Get("IBlockTypeId", 0);
            if (typeId > 0)
                iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Type.ID,BXSqlFilterOperators.Equal,typeId));
        }
        if (!string.IsNullOrEmpty(DesignerSite))
            iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Sites.SiteId,BXSqlFilterOperators.Equal,DesignerSite));

        List<BXParamValue> iblocks = new List<BXParamValue>();
        BXIBlockCollection iblockCollection = BXIBlock.GetList(iblockFilter, new BXOrderBy(new BXOrderByPair(BXIBlock.Fields.Sort, BXOrderByDirection.Asc)));
        foreach (BXIBlock b in iblockCollection)
            iblocks.Add(new BXParamValue(string.Format("[{0}] {1}", b.Id, b.Name), b.Id.ToString()));

        ParamsDefinition["IBlockId"].Values = iblocks;

        foreach (string parDefKey in ParamsDefinition.Keys)
            ParamsDefinition[parDefKey].AdjustPresentation(this);
    }

    public override void ProcessMessage(BXCommand cmd, bool executionContext, string executionVirtualPath)
    {
        if (cmd.Action == "Bitrix.Search.ProvideUrl")
        {
            if (cmd.Parameters.Get<string>("moduleId") != "iblock")
                return;
            int iblockId = Parameters.Get<int>("IBlockId", -1);
            if (iblockId < 0 || cmd.Parameters.Get<int>("itemGroup") != iblockId)
                return;
            int elementId = cmd.Parameters.Get<int>("itemId", -1);
            if (elementId < 0)
                return;

            BXParamsBag<object> p = new BXParamsBag<object>();
            p.Add("PhotoId", elementId);

            string url;
            if (Parameters.Get<bool>("EnableSEF"))
                url = MakeLink(Parameters.Get<string>("SEFFolder"), Parameters.Get<string>("SEF_Photo", "/photo/#PHOTOID#"), p);
            else
                url = MakeLink(string.Format("{0}?{1}=#PhotoId#", VirtualPathUtility.ToAbsolute(executionVirtualPath), Parameters.Get<string>("ParamPhoto", "photo")), p);

            cmd.AddCommandResult("bitrix:photogallery@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, url));
        }
    }
}
