using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
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 Bitrix;
using Bitrix.Services;
using System.Collections.Generic;

using Bitrix.IO;
using Bitrix.DataTypes;
using Bitrix.Configuration;
using Bitrix.Services.Text;

public partial class BXCustomTypeFileEdit : Bitrix.UI.BXControl, IBXCustomTypeEdit, INamingContainer
{
	//FIELDS
	private BXCustomField field;
	private int? maxSize;
	private string[] extensions;
    private BXCustomProperty value;
	private bool addDescription;

	//PROPERTIES
	public bool HasValue
	{
		get { return !(string.IsNullOrEmpty(CachedName.Value) && string.IsNullOrEmpty(StoredId.Value)); }
	}
	public string UploadBoxStyle
	{
		get { return HasValue ? "display:none;visibility:hidden;" : "display:inline;visibility:visible;"; }
	}
	public string ClearButtonStyle
	{
		get { return HasValue ? "display:inline;visibility:visible;" : "display:none;visibility:hidden;"; }
	}
	public string SaveFileName
	{
		get { return CachedName.Value ?? string.Empty; }
	}

	//METHODS
	protected void Page_Load(object sender, EventArgs e)
	{
		DataBindChildren();
	}
	protected void Page_PreRender(object sender, EventArgs e)
	{
		SavedName.InnerHtml = string.Empty;
		if (!String.IsNullOrEmpty(DisplayName.Value))
			SavedName.InnerHtml += GetMessage("File") + ": " + HttpUtility.HtmlEncode(DisplayName.Value) + "<br/>";

		if (!String.IsNullOrEmpty(DisplaySize.Value))
			SavedName.InnerHtml += GetMessage("Size") + ": " + HttpUtility.HtmlEncode(DisplaySize.Value) + "<br/>";

		if (!Page.ClientScript.IsClientScriptIncludeRegistered(GetType(), "Upload"))
			Page.ClientScript.RegisterClientScriptInclude(GetType(), "Upload", ResolveClientUrl("edit.aspx") + "?lang=" + HttpUtility.UrlEncode(BXLoc.CurrentLocale));
	}

	#region IBXCustomTypeEdit Members

	private string validationGroup = String.Empty;
	public string ValidationGroup
	{
		get { return validationGroup; }
		set { validationGroup = value; }
	}

    public void Initialize(BXCustomField currentField, BXCustomProperty currentValue)
	{
		field = currentField;
		if (field == null)
			return;

		BXParamsBag<object> settings = new BXParamsBag<object>(currentField.Settings);

		RequiredValidator.Enabled = currentField.Mandatory;
		if (RequiredValidator.Enabled)
			RequiredValidator.ErrorMessage = GetMessageFormat("Error.Required", field.EditFormLabel);

		SizeValidator.Enabled = settings.ContainsKey("MaxSize");
		if (SizeValidator.Enabled)
		{
			maxSize = (int)settings["MaxSize"];
			SizeValidator.ErrorMessage = GetMessageFormat("Error.IllegalSize", field.EditFormLabel, settings["MaxSize"]);
		}

		if (settings.ContainsKey("AllowedExtensions"))
			extensions = settings["AllowedExtensions"] as string[];
		ExtensionValidator.Enabled = (extensions != null && extensions.Length > 0);
		if (ExtensionValidator.Enabled)
			ExtensionValidator.ErrorMessage = GetMessageFormat("Error.IllegalExtension", field.EditFormLabel, string.Join(", ", extensions));
        value = currentValue;

		RequiredValidator.Enabled = field.Mandatory;
		if (RequiredValidator.Enabled)
			RequiredValidator.ErrorMessage = GetMessageFormat("Error.Required", field.EditFormLabel);

		addDescription = settings.GetBool("AddDescription");
		DescriptionBlock.Visible = addDescription;

		BXFile f = null;
		if (currentValue != null && (currentValue.Value != null && (int)currentValue.Value != 0) && (f = BXFile.GetById((int)currentValue.Value, BXTextEncoder.EmptyTextEncoder)) != null)
		{
			StoredId.Value = "Y";
			DisplayName.Value = f.FileNameOriginal;
			DisplaySize.Value = BXStringUtility.BytesToString(f.FileSize);
			if (addDescription)
				Description.Text = f.Description;
		}
	}

	public void Save(BXCustomPropertyCollection storage)
	{
		if (field == null)
			return;
		
		object value = null;
		BXCustomType t = BXCustomTypeManager.GetCustomType(field.CustomTypeId);
		
		BXFile f = null;
		if (!String.IsNullOrEmpty(CachedName.Value) && CachedName.Value.IndexOfAny(Path.GetInvalidFileNameChars()) == -1)
		{
			string filePath = BXPath.ToPhysicalPath(BXPath.Combine(BXConfigurationUtility.Constants.FileCachePath, SaveFileName + ".temp.cs")); 
			FileInfo info = new FileInfo(filePath);
			if (!info.Exists)
				return;
			using (FileStream fs = new FileStream(filePath, FileMode.Open))
			{
				f = new BXFile(fs, (DisplayName.Value.IndexOfAny(Path.GetInvalidFileNameChars()) == -1) ? DisplayName.Value : CachedName.Value, "uf", "main", string.Empty);
				BXSecureIO.DemandUpload(f.FileVirtualPath);
				if (addDescription)
					f.Description = Description.Text;
				f.Save();
			}
			value = f.Id;
			File.Delete(filePath);
		}

		if (value != null)
		{
			storage[field.Name] = new BXCustomProperty(field.Name, field.Id, t.DbType, t.IsClonable ? false : field.Multiple, value, true);
			StoredId.Value = "Y";
			DisplayName.Value = f.FileNameOriginal;
			DisplaySize.Value = BXStringUtility.BytesToString(f.FileSize);
			CachedName.Value = string.Empty;
		}
		else if (string.IsNullOrEmpty(StoredId.Value))
		{
			storage[field.Name] = new BXCustomProperty(field.Name, field.Id, t.DbType, t.IsClonable ? false : field.Multiple, null, true);
			StoredId.Value = string.Empty;
			DisplayName.Value = string.Empty;
			DisplaySize.Value = string.Empty;
			CachedName.Value = string.Empty;
		}
	}

	#endregion

	protected void SizeValidator_ServerValidate(object source, ServerValidateEventArgs args)
	{
		args.IsValid = false;
		if (maxSize.HasValue)
		{
			if (!String.IsNullOrEmpty(CachedName.Value) && CachedName.Value.IndexOfAny(Path.GetInvalidFileNameChars()) == -1)
			{
				string filePath = BXPath.ToPhysicalPath(BXPath.Combine(BXConfigurationUtility.Constants.FileCachePath, CachedName.Value));
				if (File.Exists(filePath))
				{
					FileInfo info = new FileInfo(filePath);
					if (info.Length > maxSize.Value)
						return;
				}
			}
		}
		args.IsValid = true;
	}
	protected void ExtensionValidator_ServerValidate(object source, ServerValidateEventArgs args)
	{
		args.IsValid = false;
		if (extensions != null && extensions.Length > 0 && !String.IsNullOrEmpty(SaveFileName))
		{
			string ext = Path.GetExtension(SaveFileName).ToLowerInvariant();
			while (ext.StartsWith("."))
				ext = ext.Substring(1);
			if (!BXSet.Contains(extensions, ext))
				return;
		}
		args.IsValid = true;
	}
	protected void RequiredValidator_ServerValidate(object source, ServerValidateEventArgs args)
	{
        args.IsValid = HasValue;
	}
}
