using System;
using Bitrix.UI;
using System.ComponentModel;
using Bitrix.Services;
using System.Web.UI.WebControls;
using Bitrix.Services.Js;
using Bitrix.IO;
using Bitrix.Services.Text;


public partial class bitrix_ui_AdminFileField : BXControl
{
    //FIELDS
    private BXFile _file;
    int _fileId;

    //PROPERTIES
    [DefaultValue(0)]
    public int MaxFileWidth
    {
        get
        {
            object o = ViewState["MaxFileWidth"];
            return (o == null) ? 0 : (int)o;
        }
        set
        {
            ViewState["MaxImageWidth"] = value;
        }
    }
    [DefaultValue(0)]
    public int MaxFileHeight
    {
        get
        {
            object o = ViewState["MaxImageHeight"];
            return (o == null) ? 0 : (int)o;
        }
        set
        {
            ViewState["MaxImageHeight"] = value;
        }
    }

    [DefaultValue(false)]
    public bool ShowDescription
    {
        get
        {
            object o = ViewState["ShowDescription"];
            return (o == null) ? false : (bool)o;
        }
        set
        {
            ViewState["ShowDescription"] = value;
        }
    }
    [DefaultValue("")]
    public string Description
    {
        get
        {
            if (ShowDescription)
                return Desc.Text;
            return string.Empty;
        }
        set
        {
            if (ShowDescription)
                Desc.Text = value;
        }
    }

    private bool editable = true;
    [DefaultValue(true)]
    public bool Editable
    {
        get { return editable; }
        set { editable = value; }
    }

	private string moduleId;
	[DefaultValue("")]
	public string ModuleId
	{
		get
		{
			return moduleId ?? "";
		}
		set
		{
			moduleId = value;
		}
	}

	private string subFolder;
	[DefaultValue("")]
	public string SubFolder
	{
		get
		{
			return subFolder ?? "";
		}
		set
		{
			subFolder = value;
		}
	}



    private bool _isFileGotById = false;
    private bool _ignorePostedFile = false;

    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public BXFile File
    {
        get
        {
            if (_file != null || _isFileGotById)
                return _file;

            if (IsPostBack && !_ignorePostedFile && Up.HasFile)
            {
                _file = new BXFile(Up.PostedFile, SubFolder, !string.IsNullOrEmpty(ModuleId)  ? ModuleId.ToLowerInvariant() : "main", null);
                _fileId = 0;
                _isFileGotById = false;
            }
            else
            {
                if (_fileId > 0)
                    _file = BXFile.GetById(_fileId, BXTextEncoder.EmptyTextEncoder);
                _isFileGotById = true;
            }
            return _file;
        }
    }

    [DefaultValue(0)]
    string FilePath
    {
        get
        {
            BXFile f = File;
            return f != null ? f.FilePath : string.Empty;
        }
    }

    public int FileId
    {
        get
        {
            return _fileId;
        }

        set
        {
            if (_fileId == value)
                return;

            _fileId = value;
            _isFileGotById = false;
            _ignorePostedFile = true;
            _file = null;
        }

    }

    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public FileUpload Upload
    {
        get
        {
            return Up;
        }
    }
    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public bool AboutFileDeletion
    {
        get { return Del.Checked; }
    }

    [DefaultValue(0)]
    int FileWidth
    {
        get
        {
            BXFile f = File;
            return f != null ? f.Width : 0;
        }
    }

    [DefaultValue(0)]
    int FileHeight
    {
        get
        {
            BXFile f = File;
            return f != null ? f.Height : 0;
        }
    }
    [DefaultValue(0)]
    int FileSize
    {
        get
        {
            BXFile f = File;
            return f != null ? f.FileSize : 0;
        }
    }

    [DefaultValue(0)]
    private bool IsImage
    {
        get
        {
            BXFile f = File;
            return f != null ? f.ContentType.ToUpper().StartsWith("IMAGE", StringComparison.Ordinal) : false;
        }
    }

    private bool IsSwf
    {
        get
        {
            BXFile f = File;
            return f != null ? f.ContentType.ToUpper().Equals("APPLICATION/X-SHOCKWAVE-FLASH", StringComparison.Ordinal) : false;
        }
    }

    /*
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
    }
    */

    protected override void OnPreRender(EventArgs e)
    {
        S.Visible = ShowDescription;

        if (!string.IsNullOrEmpty(FilePath))
        {
            D.Visible = true;
            Lbl.Visible = true;
            if (IsImage)
            {
                int w = FileWidth;
                int h = FileHeight;
                ImageDisplay.ImageUrl = FilePath;
                FileParameters.Text = string.Format(
                    "{0}: {1}<br/>{2}: {3}<br/>{4}: {5}<br/>{6}: {7}<br/>",
                    GetMessage("LiteralTextPartFile.ImageParameters"), Encode(FilePath),
                    GetMessage("LiteralTextPartWidth.ImageParameters"), w,
                    GetMessage("LiteralTextPartHeight.ImageParameters"), h,
                    GetMessage("LiteralTextPartSize.ImageParameters"), Encode(BXStringUtility.BytesToString(FileSize))
                    );

                if (MaxFileWidth > 0 && w > MaxFileWidth)
                {
                    h = h * MaxFileWidth / w;
                    w = MaxFileWidth;
                }

                if (MaxFileHeight > 0 && h > MaxFileHeight)
                {
                    w = w * MaxFileHeight / h;
                    h = MaxFileHeight;
                }

                ImageDisplay.Width = w;
                ImageDisplay.Height = h;

                Img.HRef = FilePath;
                Img.Attributes["onclick"] = string.Format(
                    "ImgShw('{0}','{1}','{2}', ''); return false;",
                    BXJSUtility.Encode(FilePath),
                    FileWidth,
                    FileHeight
                    );
            }
            else if (IsSwf)
            {
                int w = FileWidth;
                int h = FileHeight;
                ImageDisplay.ImageUrl = FilePath;
                FileParameters.Text = string.Format(
                    "{0}: {1}<br/>{2}: {3}<br/>{4}: {5}<br/>{6}: {7}<br/>",
                    GetMessage("LiteralTextPartFile.ImageParameters"), Encode(FilePath),
                    GetMessage("LiteralTextPartWidth.ImageParameters"), w,
                    GetMessage("LiteralTextPartHeight.ImageParameters"), h,
                    GetMessage("LiteralTextPartSize.ImageParameters"), Encode(BXStringUtility.BytesToString(FileSize))
                    );
                Img.Visible = false;

                Page.ClientScript.RegisterStartupScript(
                    GetType(),
                    string.Concat("SwfCreateClientObject_", ID),
                    string.Format(
                        "Bitrix.SwfUtility.getInstance().createElement('{0}', '{1}', {2}, {3}, null, null, null);",
                        SwfContainer.ClientID,
                        BXJSUtility.Encode(FilePath),
                        w,
                        h),
                    true
                    );
            }
            else
            {
                FileParameters.Text = string.Format(
                    "{0}: {1}<br/>{2}: {3}<br/>",
                    GetMessageRaw("LiteralTextPartFile.ImageParameters"), 
                    Encode(FilePath),
                    GetMessageRaw("LiteralTextPartSize.ImageParameters"), 
                    Encode(BXStringUtility.BytesToString(FileSize))
                    );
                Img.Visible = false;
            }
        }
        base.OnPreRender(e);
    }
}
