﻿/*
Required modules:
	eKonx.Cache
	eKonx.Base
	eKonx.Res
usage:
new eKonx.FileUploader(config)
- config overrides all default properties

or see eKonx.Profile comments to add additional items


additional config options:

onUploadFinished(form, uploadedFileID)
- event which invoked after file uploaded:
	form - file upload form instance
	uploadedFileID - id of new uploaded file
onServerAction: string
	- full type name and static method name which assignable from FileController, for example
		"eKonx.Controllers.ObjectsController.FileUploaded"
		method should with following signature:
			public static bool <methodName>(FileActionEventArgs eventArgs)
			where FileActionEventArgs:
				FileAction - action with file (delete, upload, etc.)
				FileID - file ID for which action is applied
				Request - current request, and see also below
		if method returns false, it can cancel current action
onServerActionArgs: object
	data passed to onServerAction method

maxFileSize
- defines max file size (in bytes, default is 100.000)
waitMsg:
- defines message showed then file uploaded (default eKonx.Res.FileUploader.WaitMessage)
waitTitle: 
- defines title showed on window then file uploaded (default eKonx.Res.FileUploader.WaitTitle)
allowAdd:
- is user can add new files (default is true)
maxFiles:
- maximum files count, which can be uploaded (default is 1)
getFileListUrl:
- url to get file list in format
{
	success: true,
	root:
	[
		{
			Name: string,
			Desciption string,
			ID: integer,
			AllowRemove: boolean
		}
		...
	]
},
getFileListParams:
	- extra parameter values to pass in getFileListUrl request
*/

Ext.ns("eKonx.Urls.FileUploader");
Ext.ns("eKonx.FileUploader");
Ext.ns("eKonx.Res.FileUploader");

eKonx.Urls.FileUploader =
{
	UploadFile: "File/UploadFile/",
	GetFile: '/File/GetFile/?id=',
	DeleteFile: '/File/DeleteFile/',
	GetFileList: '/File/GetEmptyFileList'
};
eKonx.Res.FileUploader =
{
	Browse: "Выбрать...",
	WaitMessage: "Файл загружается...",
	WaitTitle: "Ожидайте...",
	EmptyText: "выберите файл",
	FileName: "Имя файла",
	FileDescription: "Описание файла",
	IDPrefix: "fu_"
}
eKonx.FileUploader = Ext.extend(
Ext.form.FormPanel,
{
	fileUploaderConfig:
	{
		fileUpload: true,
		allowAdd: true,
		//frame: true,
		labelWidth: 150,
		//defaults: { anchor: "100%" },
		buttonAlign: 'right',
		items:
		[
			{
				xtype: 'textfield',
				anchor: "100%",
				fieldLabel: eKonx.Res.FileUploader.FileDescription,
				name: eKonx.Res.FileUploader.IDPrefix + 'Description'
			},
			{
				xtype: 'fileuploadfield',
				anchor: "100%",
				emptyText: eKonx.Res.FileUploader.EmptyText,
				buttonCfg:
				{
					width: 80
				},
				fieldLabel: eKonx.Res.FileUploader.FileName,
				name: eKonx.Res.FileUploader.IDPrefix + 'FilePath',
				buttonText: eKonx.Res.FileUploader.Browse
			},
	        {
	        	xtype: 'panel',
	        	border: false,
	        	fbar:
				[
					{
						xtype: "label",
						text: "Фото в формате JPG, не более 450 пикселей в ширину и высоту. Допустимое количество - 10 файлов."
					},
					{
						xtype: "tbfill"
					},
					{
						xtype: 'button',
						text: eKonx.Res.Common.SaveButton,
						id: "fileSaveButton",
						width: 80,
						handler: function()
						{
							var formPanel = this.ownerCt.ownerCt.ownerCt;
							var form = formPanel.getForm();
							if (form.isValid())
							{
								form.submit(
								{
									url: eKonx.Urls.FileUploader.UploadFile,
									waitMsg: (form.waitMsg ? form.waitMsg : eKonx.Res.FileUploader.WaitMessage),
									waitTitle: (form.waitTitle ? form.waitTitle : eKonx.Res.FileUploader.WaitTitle),
									params: Ext.apply(form.onServerActionArgs ? form.onServerActionArgs : {},
									{
										MaxFileSize: (form.maxFileSize ? form.maxFileSize : 100000),
										OnServerAction: form.onServerAction
									}),
									success: function(fp, o)
									{
										//WhatAFuck.call(this, formPanel, o);
										if (form.onUploadFinished)
											form.onUploadFinished(formPanel, o.result.data.ID);
										formPanel.findById(eKonx.Res.FileUploader.IDPrefix + "FilesGrid").getStore().reload();
									}
								});
							}
						}
					}
				]
	        },
			{
				xtype: 'editorgrid',
				id: eKonx.Res.FileUploader.IDPrefix + "FilesGrid",
				border: false,
				defaults: { anchor: "100%" },
				height: 300,

				columns:
				[
					{
						header: eKonx.Res.FileUploader.FileName,
						dataIndex: "Name"
					},
					{
						dataIndex: "ThumbnailUrl",
						renderer: function(val)
						{
							return "<img src='" + val + "'/>";
						}
					},
					{
						header: eKonx.Res.FileUploader.FileDescription,
						dataIndex: "Description"
					},
					{
						header: "",
						width: 35,
						dataIndex: "ID",
						isAction: true,
						click: function(column, rowIndex, data)
						{
							//if (!data.AllowRemove) return false;
							var form = this.grid.ownerCt;
							//remove file
							eKonx.Ajax(
							{
								url: eKonx.Urls.FileUploader.DeleteFile,
								params: Ext.apply(form.onServerActionArgs ? form.onServerActionArgs : {},
									{
										OnServerAction: form.onServerAction,
										ID: data.ID
									})
							});
							this.grid.getStore().reload();
							return false;
						},
						renderer: function(val)
						{
							return "<img src='../../I/Actions/Del.gif' style='cursor:hand'/>";
						}
					},
					null
				],
				plugins: [null],
				sm: eKonx.UI.GetCellSelectionModel(),
				store: new Ext.data.JsonStore(
				{
					storeId: eKonx.Res.FileUploader.IDPrefix + 'FileListStore',
					root: "root",
					autoSave: false,
					autoLoad: true,
					remoteSort: true,
					idProperty: 'ID',
					proxy: new Ext.data.HttpProxy(
					{
						api:
						{
							read: eKonx.Urls.FileUploader.GetFileList
						},
						method: 'POST'
					}),
					baseParams: {},
					fields:
					[
						{ name: "Name" },
						{ name: "Desciption" },
						{ name: "ID" },
						{ name: "FileName" },
						{ name: "ThumbnailUrl" },
						{ name: "IsAnnounce" }
					]
				})
			}
		]
	},
	Load: function()
	{
		if (!this.getFileListUrl) return;
		var st = this.findById(eKonx.Res.FileUploader.IDPrefix + "FilesGrid").getStore();
		//st.autoLoad = true;
		st.baseParams = this.getFileListParams ? this.getFileListParams : {};
		st.proxy = new Ext.data.HttpProxy(
		{
			api:
			{
				read: this.getFileListUrl
				//update: eKonx.Urls.RieltObjects.SaveRieltObjects
			},
			method: 'POST'
		});
		st.reload();
	},
	constructor: function(config)
	{
		var resultConfig = Ext.apply({}, this.fileUploaderConfig);

		var cc = new Ext.grid.CheckColumn(
		{
			header: "В анонс",
			dataIndex: 'IsAnnounce',
			width: 55,
			click: function(grid, record, dataIndex, val)
			{
				var id = val ? record.data.ID : null;
				eKonx.Ajax(
				{
					url: "Objects/SetAnnounceImage",
					params:
					{
						fileID: id,
						addressID: config.AddressID
					},
					success: function()
					{
						eKonx.Mediator.fireEvent(eKonx.Events.RieltObjectChanged, rieltForm.Data);
					}
				});
				grid.getStore().reload();
			}
		});
		resultConfig.items[3].plugins[0] = cc;
		resultConfig.items[3].columns[4] = cc;

		eKonx.FileUploader.superclass.constructor.call(
			this,
			eKonx.ApplyConfigWithItems(resultConfig, config));
	}
});

