using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using Bitrix;
using Bitrix.Components;
using Bitrix.Configuration;
using Bitrix.DataLayer;
using Bitrix.IBlock;
using Bitrix.IO;
using Bitrix.Security;
using Bitrix.Services;
using Bitrix.Services.Text;
using Bitrix.UI;


public class BXTemplateIBlockElement
{
	public BXTemplateIBlockElement()
	{
	}

	// properties
	/// <summary>
	/// Числовой код элемента информационного блока
	/// </summary>
	public int ElementId;
	// Символьный код элемента информационного блока
	public string Code;
	// Числовой код информационного блока
	public int IBlockId;
	// Название элемента информационного блока
	public string Name;
	// Отформатированная дата публикации элемента
	public string DisplayDate;
	// Ссылка на страницу детального просмотра
	public string DetailUrl;
	// Описание
	public string Description;
	// Изображение
	public BXFile Image;
	// Оригинальный элемент типа BXIBlockElement
	public BXInfoBlockElementOld IBlockElement;
}

public partial class RssOut : BXComponent
{
	#region Params
	public int IBlockId
	{ get { return Parameters.Get<int>("IBlockId");} }
	public int IBlockTypeId
	{ get { return Parameters.Get<int>("IBlockTypeId"); } }
	public int IBlockSectionId
	{ get { return Parameters.Get<int>("IBlockSectionId"); } }
	#endregion

	#region Results

	// Список выбранных элементов
	public List<BXTemplateIBlockElement> Items
	{get {return (List<BXTemplateIBlockElement>)Results["Items"];}}

	// Параметры информационного блока
	public BXInfoBlockOld IBlock;

	// Параметры секции
	public BXInfoBlockSectionOld IBlockSection;

	// Наименование инфоблока для XML
	public string IBlockName
	{ get { return Results.Get<string>("IBlockName"); } }

	// Описание инфоблока для XML
	public string IBlockDescription
	{ get { return Results.Get<string>("IBlockDescription"); } }

	// Название группы для XML
	public string IBlockSectionName
	{ get { return Results.Get<string>("IBlockSectionName"); } }

	// Описание группы для XML
	public string IBlockSectionDescription
	{ get { return Results.Get<string>("IBlockSectionDescription"); } }

	public string SiteName
	{
		get { return BXStringUtility.XmlEncode(BXSite.Current.Name); }
	}

	public string SiteUrl
	{
		get { return BXStringUtility.XmlEncode(BXSite.Current.ServerName); }
	}

	public string SiteDirectory
	{
		get { return BXStringUtility.XmlEncode(BXSite.Current.Directory); }
	}
	
	#endregion

	protected void Page_Load(object sender, EventArgs e)
	{
		Response.Buffer = true;

		Parameters["IBlockTypeId"] = Parameters.Get("IBlockTypeId", 0).ToString();
		Parameters["IBlockId"] = Parameters.Get("IBlockId", 0).ToString();
		Parameters["IBlockSectionId"] = Parameters.Get("IBlockSectionId", 0).ToString();
		Parameters["ElementsCount"] = Parameters.Get("ElementsCount", 20).ToString();
		Parameters["DaysCount"] = Parameters.Get("DaysCount", 0).ToString();
		Parameters["RssTTL"] = Parameters.Get("RssTTL", 60).ToString();

		if (!IsCached((Page.User as BXPrincipal).GetAllRoles(true)))
		{
			List<BXTemplateIBlockElement> items = new List<BXTemplateIBlockElement>();
			Results["Items"] = items;
			if (IBlockId > 0)
			{
				BXFormFilter iblockFilter = new BXFormFilter(
						new BXFormFilterItem("ID", IBlockId, BXSqlFilterOperators.Equal),
						new BXFormFilterItem("Active", "Y", BXSqlFilterOperators.Equal)
					);

				if (IBlockTypeId>0)
					iblockFilter.Add(new BXFormFilterItem("typeid", IBlockTypeId, BXSqlFilterOperators.Equal));

				BXInfoBlockCollectionOld iblockCollection = BXInfoBlockManagerOld.GetList(iblockFilter,	null);

				foreach (BXInfoBlockOld iblock in iblockCollection)
				{
					IBlock = iblock;

					Results["IBlockName"] = BXStringUtility.XmlEncode(IBlock.NameRaw);
					Results["IBlockDescription"] = BXStringUtility.XmlEncode(IBlock.DescriptionRaw);

					BXFormFilter elementFilter = new BXFormFilter(
						new BXFormFilterItem("IBlockId", iblock.IBlockId, BXSqlFilterOperators.Equal),
						new BXFormFilterItem("Active", "Y", BXSqlFilterOperators.Equal),
						new BXFormFilterItem("ActiveDate", "Y", BXSqlFilterOperators.Equal),
						new BXFormFilterItem("CheckPermissions", "Y", BXSqlFilterOperators.Equal)
					);

					if (Parameters.Get<int>("DaysCount") > 0)
					{
						elementFilter.Add(new BXFormFilterItem("ActiveFromDate", DateTime.Now.AddDays(-Parameters.Get<int>("DaysCount")), BXSqlFilterOperators.Greater));
					}

					if (IBlockSectionId > 0)
					{
						elementFilter.Add(new BXFormFilterItem("Section.Id", IBlockSectionId, BXSqlFilterOperators.Equal));

						BXFormFilter sectionFilter = new BXFormFilter(
							new BXFormFilterItem("IBlockId", iblock.IBlockId, BXSqlFilterOperators.Equal),
							new BXFormFilterItem("Active", "Y", BXSqlFilterOperators.Equal),
							new BXFormFilterItem("ActiveGlobal", "Y", BXSqlFilterOperators.Equal),
							new BXFormFilterItem("ID", IBlockSectionId, BXSqlFilterOperators.Equal)
						);

						BXInfoBlockSectionCollectionOld sectionCollection = BXInfoBlockSectionManagerOld.GetList(sectionFilter, null);
						if (sectionCollection.Count > 0)
						{
							IBlockSection = sectionCollection[0];
							Results["IBlockSectionName"] = BXStringUtility.XmlEncode(IBlockSection.NameRaw);
							Results["IBlockSectionDescription"] = BXStringUtility.XmlEncode(IBlockSection.DescriptionRaw);
						}
					}

					// TODO: передавать сортировку из параметров
					BXOrderBy_old elementOrderBy = new BXOrderBy_old("ActiveFromDate", "DESC");
					elementOrderBy.Add("Sort", "Asc");
					elementOrderBy.Add("ID", "Desc");

					BXInfoBlockElementCollectionOld elementCollection = BXInfoBlockElementManagerOld.GetList(
						elementFilter,
						elementOrderBy,
						null,
						new BXQueryParams(new BXPagingOptions(0, Parameters.Get<int>("ElementsCount")))
					);
					foreach (BXInfoBlockElementOld element in elementCollection)
					{
						BXTemplateIBlockElement item = new BXTemplateIBlockElement();
						item.ElementId = element.ElementId;
						item.Code = BXStringUtility.XmlEncode(element.CodeRaw);
						item.IBlockId = element.IBlockId;
						item.Name = BXStringUtility.XmlEncode(element.NameRaw);
						item.Image = element.PreviewImage;
						item.Description = BXStringUtility.XmlEncode(element.PreviewTextRaw);

						string displayDate = "";
						if (element.ActiveFromDate != DateTime.MinValue)
							displayDate = element.ActiveFromDate.ToString("r");
						else
							displayDate = "";
						item.DisplayDate = displayDate;

						string detailUrl = null;
						if (Parameters.ContainsKey("DetailUrl") && !String.IsNullOrEmpty(Parameters["DetailUrl"]))
						{
							string str = Parameters["DetailUrl"].Replace("#SITE_DIR#", BXSite.Current.Directory);
							str = str.Replace("#IBLOCK_ID#", iblock.IBlockId.ToString());
							str = str.Replace("#SECTION_ID#", (element.Sections.Count > 0) ? element.Sections[0].ToString() : "");
							str = str.Replace("#ELEMENT_ID#", element.ElementId.ToString());
							Results["IBlockId"] = iblock.IBlockId;
							Results["SectionId"] = (element.Sections.Count > 0) ? element.Sections[0].ToString() : "";
							Results["ElementId"] = element.ElementId;
							str = BXUri.ToRelativeUri(BXComponentManager.MakeLink(str, Results)).Replace("//", "/");
							detailUrl = BXStringUtility.XmlEncode(str);
						}
						item.DetailUrl = detailUrl;
						items.Add(item);
					}
				}
			}

			IncludeComponentTemplate();
		}
	}

	protected override void Render(HtmlTextWriter writer)
	{
		if (IsComponentDesignMode || BXConfigurationUtility.IsDesignMode)
		{
			HtmlTextWriter writer2 = new HtmlTextWriter(new System.IO.StringWriter(System.Globalization.CultureInfo.CurrentCulture));
			base.Render(writer2);
			if (BXConfigurationUtility.IsDesignMode)
				writer.Write("<pre style='width:500px;overflow:scroll;'>");
			else
				writer.Write("<pre>");
			writer.Write(HttpUtility.HtmlEncode(writer2.InnerWriter.ToString())+"</pre>");
		}
		else
		{
			Response.Buffer = true;
			writer.Flush();
			Response.Clear();
			HtmlTextWriter writer2 = new HtmlTextWriter(new System.IO.StringWriter(System.Globalization.CultureInfo.CurrentCulture));
			base.Render(writer2);
			Response.ContentType = "text/xml";
			Response.Write(writer2.InnerWriter.ToString());
			Response.End();
		}
	}

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

		ParamsDefinition.Add(BXParametersDefinition.Cache);

		//Group = new BXComponentGroup("rss", "RSS", 100, BXComponentGroup.Content);

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

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

		ParamsDefinition.Add(
			"IBlockSectionId",
			new BXParamText(
				GetMessageRaw("GroupID"),
				"0",
				BXCategory.Main
			)
		);
		ParamsDefinition["IBlockSectionId"].RefreshOnDirty = true;

		ParamsDefinition.Add(
			"ElementsCount",
			new BXParamText(
				GetMessageRaw("ExportedElementsCount"),
				"20",
				BXCategory.Main
			)
		);
		ParamsDefinition["ElementsCount"].RefreshOnDirty = true;

		ParamsDefinition.Add(
			 "DaysCount",
			 new BXParamText(
				 GetMessageRaw("ExportedDaysCount"),
				 "0",
				 BXCategory.Main
			 )
		 );

		ParamsDefinition["DaysCount"].RefreshOnDirty = true;

		ParamsDefinition.Add(
			 "DetailUrl",
			 new BXParamText(
				 GetMessageRaw("DetailPage"),
				 "/default.aspx?news=#ELEMENT_ID#",
				 BXCategory.Main
			 )
		 );


		BXCategory rssCategory = new BXCategory(GetMessageRaw("RssSettings"), "RssSettings", 100);

		ParamsDefinition.Add(
			"RssTTL",
			new BXParamText(
				GetMessageRaw("TimeToLiveInMinutes"),
				"60",
				rssCategory
			)
		);
	}

	protected override void LoadComponentDefinition()
	{
		List<BXParamValue> iblockTypes = new List<BXParamValue>();
 		BXInfoBlockTypeCollectionOld typeCollection = BXInfoBlockTypeManagerOld.GetList(null, new BXOrderBy_old("Sort", "Asc"));
		foreach (BXInfoBlockTypeOld t in typeCollection)
            iblockTypes.Add(new BXParamValue(t.TypeLang[BXLoc.CurrentLocale].Name, t.TypeId.ToString()));

		ParamsDefinition["IBlockTypeId"].Values = iblockTypes;

		BXFormFilter iblockFilter = new BXFormFilter();
		if (Parameters.ContainsKey("IBlockTypeId"))
		{
			int typeId;
			int.TryParse(Parameters["IBlockTypeId"], out typeId);
			if (typeId > 0)
				iblockFilter.Add(new BXFormFilterItem("TypeId", typeId, BXSqlFilterOperators.Equal));
		}

        if (!string.IsNullOrEmpty(DesignerSite))
            iblockFilter.Add(new BXFormFilterItem("Site.Id", DesignerSite, BXSqlFilterOperators.Equal));

		List<BXParamValue> iblocks = new List<BXParamValue>();
		BXInfoBlockCollectionOld iblockCollection = BXInfoBlockManagerOld.GetList(iblockFilter, new BXOrderBy_old("Sort", "Asc"));
		foreach (BXInfoBlockOld b in iblockCollection)
			iblocks.Add(new BXParamValue(b.Name, b.IBlockId.ToString()));

		ParamsDefinition["IBlockId"].Values = iblocks;

		base.LoadComponentDefinition();
	}
}
