Ext.define('FileRun.controller.FilePanel', {
	extend: 'Ext.app.Controller',
	config: {
		refs: {
			frm: 'filepanel',
			topBar: '#FilePanelTopBar',
			mainView: 'mainview',
			backToListBtn: 'button[action=backToList]',
			downloadBtn: 'button[action=download]',
			previewBtn: 'button[action=preview]',
			openWithBtn: 'button[action=openWith]',
			moreBtn: 'button[action=more]',
			delBtn: 'button[action=del]',
			webLinkBtn: 'button[action=weblink]',
			BTSyncBtn: 'button[action=btsync]',
			openWebLinkAsBtn: 'button[action=openWebLinkAs]',
			owlAsGalleryBtn: 'button[action=openWebLinkAsGallery]',
			owlAsPlaylistBtn: 'button[action=openWebLinkAsPlaylist]',
			owlAsRSSBtn: 'button[action=openWebLinkAsRSS]',
			webLinkUrl: '#webLinkUrl',
			webLinkExpiry: '#wlexpiry',
			webLinkPass: '#wlpass',
			webLinkShort: '#wlshort',
			filenameField: 'textfield[name=filename]'
		},
		control: {
			backToListBtn: {tap: 'goBack'},
			downloadBtn: {tap: 'download'},
			previewBtn: {tap: 'preview'},
			openWithBtn: {tap: 'showOpenWith'},
			BTSyncBtn: {tap: 'btsync'},
			openWebLinkAsBtn: {tap: 'showOpenAs'},
			owlAsGalleryBtn: {tap: function() {this.openWebLinkAs('gallery');}},
			owlAsPlaylistBtn: {tap: function() {this.openWebLinkAs('playlist');}},
			owlAsRSSBtn: {tap: function() {this.openWebLinkAs('rss');}},
			moreBtn: {tap: 'showMore'},
			delBtn: {tap: 'del'},
			webLinkBtn: {tap: 'toggleWebLink'},
			filenameField: {action: 'ren'},
			webLinkExpiry: {change: 'updateWebLink'},
			webLinkPass: {change: 'updateWebLink'},
			webLinkShort: {change: 'getShortWebLink'}
		}
	},
	'load': function() {
		this.getFrm().setRecord(FR.currentItem);
		this.getTopBar().setTitle(FR.currentItem.data.filename);
		if (FR.currentItem.data.is_dir) {
			this.getFrm().getFields().nicerFileSize.hide();
		} else {
			this.getFrm().getFields().nicerFileSize.show();
		}
		this.getPreviewBtn().setHidden((FR.currentItem.data.is_dir || !FR.currentFolderPerms.download));
		this.getDownloadBtn().setHidden((FR.currentItem.data.is_dir || !FR.currentFolderPerms.download));
		this.getMoreBtn().setHidden((!FR.currentFolderPerms || !FR.currentFolderPerms.download));
		this.setWebLink();
		this.getFrm().getFields().btsyncReadOnly.up('fieldset').setHidden(true);
		this.getFrm().getFields().btsyncReadOnly.setValue();
		this.getFrm().getFields().btsyncReadWrite.setValue();
	},
	'goBack': function() {
		this.getFrm().setRecord({});
		Ext.Viewport.setActiveItem(this.getMainView());
	},
	'showMore': function() {
		if (!this.moreMenu) {
			this.moreMenu = Ext.create('FileRun.view.FilePanelMore');
			Ext.Viewport.add(this.moreMenu);
		}
		var delBtn = this.getDelBtn();
		var webLinkBtn = this.getWebLinkBtn();
		var BTSyncBtn = this.getBTSyncBtn();
		var openWebLinkAsBtn = this.getOpenWebLinkAsBtn();
		if (FR.currentItem.data.weblink) {
			webLinkBtn.setText(FR.T('Remove WebLink'));
		} else {
			webLinkBtn.setText(FR.T('Generate WebLink'));
		}
		var openWithBtn = this.getOpenWithBtn();
		if (FR.currentItem.data.is_dir) {
			openWebLinkAsBtn.setHidden(!FR.currentItem.data.weblink);
			delBtn.hide();
			openWithBtn.hide();
			BTSyncBtn.show();
		} else {
			BTSyncBtn.hide();
			openWebLinkAsBtn.setHidden(true);
			delBtn.setHidden(!FR.currentFolderPerms.alter);
			if (FR.ext[FR.currentItem.data.ext]) {
				openWithBtn.show();
			} else {
				openWithBtn.hide();
			}
		}
		this.moreMenu.showBy(this.getMoreBtn());
	},
	'showOpenAs': function() {
		if (!this.openWebLinkAsMenu) {
			this.openWebLinkAsMenu = Ext.create('FileRun.view.FilePanelOpenWlAs');
			Ext.Viewport.add(this.openWebLinkAsMenu);
		}
		this.moreMenu.hide();
		this.openWebLinkAsMenu.show('pop');
	},
	'openWebLinkAs': function(mode) {
		window.open(FR.currentItem.data.weblink.url+'&mode='+mode);
		this.moreMenu.hide();
	},
	'showOpenWith': function() {
		if (!this.openWithMenu) {
			this.openWithMenu = Ext.create('FileRun.view.FilePanelOpenWith');
			Ext.Viewport.add(this.openWithMenu);
		}
		this.moreMenu.hide();
		this.openWithMenu.removeAll();
		var i = 0;
		Ext.each(FR.ext[FR.currentItem.data.ext], function(aName) {
			i++;
			var ca = FR.customActions[aName];
			this.openWithMenu.add({text: ca.title, icon: '../'+ca.icon, style: (i < FR.ext[FR.currentItem.data.ext].length ? 'margin-bottom:5px' : ''), handler: function() {
				if (ca.popup) {
					var url = '../?module=custom_actions&action='+ca.actionName;
					url += '&path='+encodeURIComponent(FR.currentPath);
					url += '&filename='+encodeURIComponent(FR.currentItem.data.filename);
					FileRun.app.getController('FileRun.controller.app').openLinkInNewWindow(url);
				} else {
					eval(ca.fn);
				}
			}});
		}, this);
		this.openWithMenu.show('pop');
	},
	'download': function() {
		var url = '../?module=fileman&section=touch&page=download&path='+encodeURIComponent(FR.currentPath);
		url += '&filename='+encodeURIComponent(FR.currentItem.data.filename);
		document.location.href = url;
	},
	'preview': function() {
		var path = FR.currentPath+'/'+FR.currentItem.data.filename;
		var url = '../?module=fileman&section=utils&page=file_preview&mobile=1&path='+encodeURIComponent(path);
		this.previewFrame = new Ext.Element(document.createElement('iframe'));
		this.previewFrame.set({width: '100%', height: '100%', border: 0, frameborder: 0});
		this.previewPanel = new Ext.Panel({
			autoDestroy: true, 
			fullscreen: true, modal: true,
			scrollable: 'vertical', padding: 0,
			contentEl: this.previewFrame,
			listeners: {
				resize: function (el, eopts) {
					this.previewFrame.set({height: el.getHeight(true)});
				}, scope: this
			},
			items: [{
				xtype: 'titlebar',
				docked: 'top',
				title: FR.currentItem.data.filename,
				items: [
					{xtype: 'button', align: 'right', text: FR.T('Close'), handler: function(el) {
						Ext.Viewport.setActiveItem(this.getFrm());
						this.previewPanel.destroy();
					}, scope: this}
				]
			}]
		});
		Ext.Viewport.add(this.previewPanel);
		Ext.Viewport.setActiveItem(this.previewPanel);
		this.previewFrame.set({src: url});
	},
	'setWebLink': function() {
		var webLinkUrl = this.getWebLinkUrl();
		var wl =  FR.currentItem.data.weblink;
		if (wl) {
			var url = wl.short_url ? wl.short_url : wl.url;

			this.getWebLinkShort().suspendEvents();
			this.getWebLinkShort().setValue(typeof wl.short_url != 'undefined' ? 1 : 0);
			this.getWebLinkShort().resumeEvents(true);

			this.getWebLinkExpiry().suspendEvents();
			this.getWebLinkExpiry().setValue(wl.expiry ? new Date(wl.expiry) : false);
			this.getWebLinkExpiry().resumeEvents(true);

			this.getWebLinkPass().suspendEvents();
			this.getWebLinkPass().setValue(wl.password);
			this.getWebLinkPass().resumeEvents(true);

			webLinkUrl.setValue(url);
		}
		webLinkUrl.up('fieldset').setHidden(!FR.currentItem.data.weblink);
	},
	'toggleWebLink': function () {
		if (!FR.currentItem.data.weblink) {
			this.getWebLink();
		} else {
			this.removeWebLink();
		}
	},
	'btsync': function() {
		this.moreMenu.hide();
		Ext.Viewport.mask();
		var fields = this.getFrm().getFields();
		fields.btsyncReadOnly.up('fieldset').setHidden(false);
		if (FR.currentItem.data.isBTSShared) {
			var url = '../?module=btsync&action=get_secrets';
		} else {
			var url = '../?module=btsync&action=add_folder';
		}
		Ext.Ajax.request({
			url: url,
			params: {path: FR.currentPath+'/'+FR.currentItem.data.filename},
			callback: function() {Ext.Viewport.unmask();},
			success: function(response, opts) {
				try {
					var rs = Ext.decode(response.responseText);
				} catch (er){return false;}
				if (rs.success) {
					FR.currentItem.data.isBTSShared=1;
				}
				if (rs.secrets){
					if (rs.secrets.read_only) {
						rs.read_only = rs.secrets.read_only;
					}
					if (rs.secrets.read_write) {
						rs.read_write = rs.secrets.read_write;
					}
				}
				if (rs.read_only || rs.read_write) {
					if (rs.read_only) {
						fields.btsyncReadOnly.setValue(rs.read_only);
					}
					if (rs.read_write) {
						fields.btsyncReadWrite.setValue(rs.read_write);
					}
				}
				if (rs.msg) {
					Ext.Msg.alert(FR.T('BitTorrent Sync'), rs.msg);
				}
			}, scope: this
		});
	},
	'updateWebLink': function () {
		Ext.Viewport.mask();
		var url = '../?module=weblinks&section=ajax&page=update&action=edit';
		var fields = this.getFrm().getFields();
		Ext.Ajax.request({
			url: url,
			params: {
				path: FR.currentPath+'/'+FR.currentItem.data.filename,
				password: fields.wlpass.getValue(),
				expiry: fields.wlexpiry.getFormattedValue()
			},
			callback: function() {Ext.Viewport.unmask();},
			success: function(response, opts) {
				try {
					var rs = Ext.decode(response.responseText);
				} catch (er){return false;}
				FR.currentItem.data.weblink.password = fields.wlpass.getValue();
				FR.currentItem.data.weblink.expiry = fields.wlexpiry.getValue();
				if (rs.msg) {
					Ext.Msg.alert(FR.T('WebLink'), rs.msg);
				}
			}, scope: this
		});
	},
	'getShortWebLink': function() {
		if (this.getWebLinkShort().getValue()) {
			if (FR.currentItem.data.weblink.short_url) {
				this.getWebLinkUrl().setValue(FR.currentItem.data.weblink.short_url);
			} else {
				Ext.Viewport.mask();
				var url = '../?module=weblinks&section=ajax&page=get_short';
				Ext.Ajax.request({
					url: url,
					params: {linkId: FR.currentItem.data.weblink.id},
					callback: function() {Ext.Viewport.unmask();},
					success: function(response, opts) {
						try {
							var rs = Ext.decode(response.responseText);
						} catch (er){return false;}
						if (rs.success) {
							FR.currentItem.data.weblink.short_url = rs.url;
							this.getWebLinkUrl().setValue(rs.url);
						} else {
							Ext.Msg.alert(FR.T('WebLink'), rs.error);
						}
					}, scope: this
				});
			}
		} else {
			this.getWebLinkUrl().setValue(FR.currentItem.data.weblink.url);
		}
	},
	'getWebLink': function() {
		this.moreMenu.hide();
		Ext.Viewport.mask();
		var url = '../?module=weblinks&section=ajax&page=update&action=create';
		Ext.Ajax.request({
			url: url,
			params: {path: FR.currentPath+'/'+FR.currentItem.data.filename},
			callback: function() {Ext.Viewport.unmask();},
			success: function(response, opts) {
				try {
					var rs = Ext.decode(response.responseText);
				} catch (er){return false;}
				if (rs.success) {
					FR.currentItem.set('weblink', {id: rs.id, url: rs.url});
					this.setWebLink();
				} else {
					Ext.Msg.alert(FR.T('WebLink'), rs.msg);
				}
			}, scope: this
		});
	},
	'removeWebLink': function() {
		this.moreMenu.hide();
		Ext.Viewport.mask();
		var url = '../?module=weblinks&section=ajax&page=update&action=remove';
		Ext.Ajax.request({
			url: url,
			params: {path: FR.currentPath+'/'+FR.currentItem.data.filename},
			callback: function() {Ext.Viewport.unmask();},
			success: function(response, opts) {
				try {
					var rs = Ext.decode(response.responseText);
				} catch (er){return false;}
				if (rs.success) {
					FR.currentItem.set('weblink', '');
					this.setWebLink();
				} else {
					Ext.Msg.alert(FR.T('WebLink'), rs.msg);
				}
			}, scope: this
		});
	},
	'ren': function() {
		Ext.Viewport.mask();
		var newName = this.getFrm().getFields().filename.getValue();
		if (FR.currentItem.data.is_dir) {
			var params = {
				path: FR.currentPath+'/'+FR.currentItem.data.filename,
				newfilename: newName
			};
			var url = '../?module=fileman_myfiles&section=ajax&page=tree_action_rename';
		} else {
			var params = {
				path: FR.currentPath,
				oldfilename: FR.currentItem.data.filename,
				newfilename: newName
			};
			var url = '../?module=fileman_myfiles&section=ajax&page=grid_action_rename';
		}
		Ext.Ajax.request({
			url: url,
			params: params,
			callback: function() {Ext.Viewport.unmask();},
			success: function(response, opts) {
				try {
					var rs = Ext.decode(response.responseText);
				} catch (er){return false;}
				if (rs.rs) {
					FR.currentItem.set('filename', newName);
				}
				Ext.Msg.alert(FR.T('Rename'), rs.msg);
			}
		});
	},
	'del': function() {
		this.moreMenu.hide();
		Ext.Msg.confirm(FR.T('Delete'), FR.T('Are you sure you want to delete the selected file?'), function(btn) {
			if (btn == 'yes') {
				Ext.Viewport.mask();
				var url = '../?module=fileman_myfiles&section=ajax&page=grid_action_delete';
				var params = 'path='+encodeURIComponent(FR.currentPath);
				params += '&filenames[]='+encodeURIComponent(FR.currentItem.data.filename);
				Ext.Ajax.request({
					url: url,
					params: params,
					callback: function() {Ext.Viewport.unmask();},
					success: function(response, opts) {
						try {
							var rs = Ext.decode(response.responseText);
						} catch (er){return false;}
						if (rs.rs) {
							this.goBack();
							FileRun.app.getController('FileRun.controller.FileList').reload();
						} else {
							Ext.Msg.alert(FR.T('Delete'), rs.msg);
						}
					}, scope: this
				});
			}
		}, this);
	}
});