Ext.define("Portfolio.ux.file.view.Explorer", {

	alternateClassName: [
		"Ext.ux.file.view.Explorer"
	],

	title: ip2.i18n({
		da: "Fil explorer",
		en: "File explorer"
	}),

	extend: "Ext.window.Window",

	alias: [
		"widget.ux.file.view.explorer",
		"widget.file.explorer"
	],

	closable: false,

	width: 800,
	height: 600,

	layout: "fit",

	bodyPadding: 5,

	modal: true,

	config: {
		path: "",
		saveAction: false,
		navigator: null,
		objectGrid: null,
		fileExtension: [
			{
				ext: "*",
				desc: "All Files (*.*)"
			}
		],
		extensionField: null,
		pathField: null,
		fileName: null,
		formPanel: null
	},

	listeners: {
		folderselect: {
			fn: function(i_self, i_record) {

				var i_panel = i_self.getFormPanel();
				var i_form = i_panel.getForm();

				var o_values = i_panel.getValues();

				Ext.apply(o_values, {
					path: ip2.cleanPath(i_record.get("id")),
					filename: ""
				});

				i_form.setValues(o_values);
			}
		},
		fileselect: {
			fn: function(i_self, i_record) {

				var i_panel = i_self.getFormPanel();
				var i_form = i_panel.getForm();

				var s_path = ip2.cleanPath(i_record.get("id"));

				if (s_path.split(".").length > 1) {

					var a_split = s_path.split(".");
					a_split.pop();

					var s_join = a_split.join("");

					a_split = s_join.split("/");
					a_split.pop();

					s_path = a_split.join("/");
				}

				var o_values = {
					filename: i_record.get("text"),
					path: s_path
				};

				i_form.setValues(o_values);
			}
		}
	},

	initComponent: function() {

		var i_self = this;

		i_self.callParent(arguments);

		i_self.createModels();

		var i_formpanel = i_self.createLayout();

		i_self.add(i_formpanel);

		i_formpanel.isValid();
	},

	createModels: function() {

		if (!Ext.ClassManager.isCreated("objectList")) {
			Ext.define("objectList", {
				extend: "Ext.data.Model",
				proxy: {
					type: "ajax",
					url: "/ip2-services/webBios.aspx",
					extraParams: {
						func: "listdir",
						metaData: true,
						sort: true
					},
					reader: {
						type: "json",
						rootProperty: "rows",
						totalProperty: "totalRows"
					}
				}
			});
		}

		if (!Ext.ClassManager.isCreated("fileExtension")) {
			Ext.define("fileExtension", {
				extend: "Ext.data.Model",fields: [
					{
						type: "string",
						name: "ext"
					},
					{
						type: "string",
						name: "desc"
					}
				]
			});
		}
	},

	createLayout: function() {

		var i_self = this;

		var i_north = i_self.createNorth();
		var i_navigator = i_self.createNavigator();
		var i_center = i_self.createCenter();
		var i_south = i_self.createSouth();

		var i_form = Ext.widget("form", {
			layout: "border",
			border: false
		});

		i_form.on({
			validityChange: {
				fn: function(i_form, b_valid) {

					var i_button = i_self.down("#explorer-button-ok");

					i_button[b_valid ? "enable" : "disable"]();
				}
			}
		});

		i_form.add([
			i_north,
			i_center,
			i_navigator,
			i_south
		]);

		i_form.addDocked(i_self.createFooter());
		i_self.setFormPanel(i_form);

		return i_form;
	},

	createNorth: function() {

		var i_self = this;

		var i_path = Ext.widget("textfield", {
			name: "path",
			fieldLabel: ip2.i18n({
				da: "Sti",
				en: "Path"
			}),
			labelWidth: 40,
			allowBlank: true,
			value: i_self.getPath(),
			enableKeyEvents: true,
			listeners: {
				specialKey: {
					fn: function(i_field, i_event) {

						if (i_event.getKey() == i_event.ENTER) {

							var i_navigator = i_self.getNavigator();
							var i_store = i_navigator.getStore();

							var s_value = i_field.getValue();
							var i_root = i_navigator.getRootNode();
							i_root.removeAll(false);

							i_self.setPath(s_value);

							i_store.load({
								node: i_root
							});
						}
					}
				}
			}
		});

		var i_panel = Ext.widget("panel", {
			region: "north",
			bodyPadding: 3,
			defaults: {
				anchor: "100%"
			},
			layout: "anchor",
			items: [
				i_path
			]
		});

		i_self.setPathField(i_path);

		return i_panel;
	},

	createCenter: function() {

		var i_self = this;

		var i_panel = Ext.widget("panel", {
			border: false,
			layout: "fit",
			region: "center",
			flex: 1,
			items: [
				i_self.createObjectGrid()
			]
		});

		return i_panel;
	},

	createSouth: function() {

		var i_self = this;

		var b_save = i_self.getSaveAction();

		var a_extensions = i_self.getFileExtension();

		var a_fields = [];

		var i_fileName = Ext.widget("textfield", {
			name: "filename",
			fieldLabel: ip2.i18n("filename"),
			allowBlank: !b_save ? true : false,
			flex: 1,
			readOnly: !b_save,
			validator: function(value) {

				var i_fileExtensions = i_self.getExtensionField();

				var b_valid = true;
				var s_pop = value.split(".").pop();
				var s_extension = i_fileExtensions.getValue();

				if (s_extension != "*") {
					b_valid = s_pop == s_extension;
				}

				if (!b_valid) {
					return ip2.i18n({
						da: "Filen skal have samme type ( " + s_extension + " )",
						en: "File must have the same extension ( " + s_extension + " )"
					});
				}

				return b_valid;
			}
		});

		a_fields.push(i_fileName);

		var i_extensionStore = Ext.create("Ext.data.Store", {
			model: "fileExtension",
			data: a_extensions
		});

		var i_fileExtensions = Ext.widget("combobox", {
			name: "extension",
			displayField: "desc",
			valueField: "ext",
			store: i_extensionStore,
			queryMode: "local",
			typeAhead: true,
			anchor: b_save ? "100%" : null,
			hideLabel: b_save ? false : true,
			fieldLabel: ip2.i18n({
				da: "Type",
				en: "Type"
			}),
			margin: "0 0 0 0",
			listeners: {
				afterrender: {
					fn: function(i_field) {

						var a_extensions = i_self.getFileExtension();

						i_field.setValue(a_extensions[0].ext);
					}
				},
				select: {
					fn: function(i_field, i_record) {

						var i_objectGrid = i_self.getObjectGrid();
						var i_store = i_objectGrid.getStore();
						var i_formpanel = i_self.getFormPanel();

						i_store.load();

						i_formpanel.isValid();
					}
				}
			}
		});

		a_fields.push(i_fileExtensions);

		var i_south = Ext.widget("panel", {
			region: "south",
			collapsible: false,
			bodyPadding: 10,
			defaults: {
				margin: "0 5 0 0"
			},
			layout: {
				type: "hbox",
				align: "stretch"
			},
			items: a_fields
		});

		i_self.setExtensionField(i_fileExtensions);

		return i_south;
	},

	createFooter: function() {

		var i_self = this;

		var b_save = i_self.getSaveAction();

		var a_items = [
			"->",
			{
				xtype: "button",
				text: ip2.i18n({
					da: "Anuller",
					en: "Cancel"
				}),
				handler: function() {
					i_self.close();
				}
			},
			{
				xtype: "button",
				text: b_save ? ip2.i18n({
					da: "Gem",
					en: "Save"
				}) : ip2.i18n({
					da: "Åben",
					en: "Open"
				}),
				itemId: "explorer-button-ok",
				disabled: b_save ? false : true,
				ui: "primary-button",
				handler: function() {

					var i_formpanel = i_self.getFormPanel();
					var o_values = i_formpanel.getValues();

					var i_objectGrid = i_self.getObjectGrid();

					var a_path = [];

					a_path.push(o_values.path);
					a_path.push(o_values.filename);

					var s_file = ip2.cleanPath(a_path.join("/"));

					if (b_save) {

						var a_batch = [
							{
								type: "call",
								pgm: "webbios",
								parms: {
									func: "checkstmf",
									file: s_file
								}
							}
						];

						Ext.Ajax.request({
							url: "/ip2-Services/ip2dmdproxy.aspx",
							jsonData: {
								batch: a_batch
							},
							success: function (o_response) {

								var o_result = Ext.decode(o_response.responseText, true);

								var b_exists = false;

								Ext.Array.each(o_result.batch, function(o_values) {

									if (o_values.exists) {
										b_exists = true;
										return false;
									}
								});

								if (b_exists) {

									ip2.messageBox({
										icon: Ext.MessageBox.WARNING,
										title: ip2.i18n("replaceExisting"),
										closable: false,
										message: Ext.String.format(ip2.i18n("fileAlreadyExists"), o_values.filename),
										yesFn: function () {
											i_self.fireEvent("filesave", i_self, s_file);
											i_self.close();
										},
										yesText: ip2.i18n({
											da: "Ja",
											en: "Yes"
										}),
										noText: ip2.i18n({
											da: "Nej",
											en: "No"
										})
									});
								}
								else {
									i_self.fireEvent("filesave", i_self, s_file);
									i_self.close();
								}
							}
						});
					}
					else {

						i_self.fireEvent("fileopen", i_self, s_file);
						i_self.close();
					}
				}
			}
		];

		var i_toolbar = Ext.widget("toolbar", {
			ui: "footer",
			dock: "bottom",
			items: a_items
		});

		return i_toolbar;
	},

	createNavigator: function() {

		var i_self = this;

		var i_navigator = Ext.widget("treepanel", {
			region: "west",
			width: 200,
			split: true,
			collapsible: false,
			lines: false,
			useArrows: true,
			autoScroll: true,
			rootVisible: false,
			frame: false,
			store: Ext.create("Ext.data.TreeStore", {
				folderSort: true,
				proxy: {
					type: "ajax",
					url: "/ip2-services/webBios.aspx"
				},
				root: {
					id: "",
					expanded: false
				}
			}),
			listeners: {
				select: {
					fn: function(i_view, i_record) {

						var i_panel = i_self.getFormPanel();
						var i_form = i_panel.getForm();

						var s_recordExtension = i_record.get("ext");
						var s_path = "";

						if (s_recordExtension == "folder") {

							var i_objectGrid = i_self.getObjectGrid();
							var i_store = i_objectGrid.getStore();

							s_path = i_self.getPath();

							if (!i_record.isRoot()) {

								var i_current = i_record;

								var a_path = [];

								while (!i_current.isRoot()) {

									a_path.unshift(i_current.get("text"));
									i_current = i_current.parentNode;
								};

								a_path.unshift(s_path);

								s_path = a_path.join("/");
							}

							s_path = ip2.cleanPath(s_path);

							i_form.setValues({
								path: s_path,
								filename: ""
							});

							i_store.load();
						}
						else{
							i_self.fireEvent("fileselect", i_self, i_record);
						}
					}
				},
				itemdblclick: {
					fn: function (i_view, i_record, i_element, n_index, i_event) {

						i_event.preventDefault();

						var s_extension = i_record.get("ext");

						var i_formpanel = i_self.getFormPanel();
						var o_values = i_formpanel.getValues();

						if (s_extension != "folder") {

							var a_path = [];

							a_path.push(o_values.path);
							a_path.push(o_values.filename);

							var s_file = ip2.cleanPath(a_path.join("/"));

							i_self.fireEvent("fileopen", i_self, s_file);

							i_self.close();
						}
					}
				},
				beforeload: {
					fn: function(i_store, i_operation) {

						var i_formpanel = i_self.getFormPanel();

						var o_values = {
							extension: "folder"
						};

						if (i_formpanel) {
							o_values = i_formpanel.getValues();
						}

						var i_node = i_operation.node;

						var s_path = i_self.getPath();

						var i_navigator = i_self.getNavigator();

						var i_selected = i_node;

						if (!i_selected.isRoot()) {

							var i_current = i_selected;

							var a_path = [];

							while (!i_current.isRoot()) {

								a_path.unshift(i_current.get("text"));
								i_current = i_current.parentNode;
							};

							a_path.unshift(s_path);

							s_path = a_path.join("/");
						}

						s_path = ip2.cleanPath(s_path);

						var i_proxy = i_store.getProxy();
						var o_params = i_proxy.getExtraParams();

						var s_extensions = o_values.extension;

						Ext.apply(o_params, {
							func: "listdir",
							extension: s_extensions,
							path: s_path,
							sort: true,
							node: null
						});

						delete i_operation.node;
					}
				}
			}
		});

		i_self.setNavigator(i_navigator);

		return i_navigator;
	},

	createObjectGrid: function() {

		var i_self = this;

		var i_grid = Ext.widget("gridpanel", {
			region: "center",
			store: Ext.create("Ext.data.Store", {
				model: "objectList",
				listeners: {
					beforeload: {
						fn: function(i_store, i_operation) {

							var i_formpanel = i_self.getFormPanel();
							var o_values = i_formpanel.getValues();

							var i_proxy = i_store.getProxy();
							var o_extraParams = i_proxy.getExtraParams();

							var s_path = o_values.path;

							if (s_path.split(".").length > 1) {

								var a_split = s_path.split(".");
								a_split.pop();

								var s_join = a_split.join("");

								a_split = s_join.split("/");
								a_split.pop();

								s_path = a_split.join("/");
							}

							Ext.apply(o_extraParams, {
								path: s_path,
								extension: o_values.extension
							});
						}
					}
				}
			}),
			columns: [
				{
					header: "",
					dataIndex: "ext",
					renderer: function(value) {

						var s_icon = "";

						var s_url = "";

						switch (value) {
							case "bmp":
								s_url = "/system/shared/collection/icons/16x16/plain/bmp.png";
								break;
							case "dbm":
								s_url = "/system/shared/collection/icons/16x16/plain/branch.png";
								break;
							case "doc":
								s_url = "/system/shared/collection/icons/16x16/plain/doc.png";
								break;
							case "docx":
								s_url = "/system/shared/collection/icons/16x16/plain/doc.png";
								break;
							case "eml":
								s_url = "/system/shared/collection/icons/16x16/plain/eml.png";
								break;
							case "folder":
								s_url = "/system/shared/collection/icons/16x16/plain/folder.png";
								break;
							case "gif":
								s_url = "/system/shared/collection/icons/16x16/plain/gif.png";
								break;
							case "htm":
								s_url = "/system/shared/collection/icons/16x16/plain/html.png";
								break;
							case "html":
								s_url = "/system/shared/collection/icons/16x16/plain/html.png";
								break;
							case "jpg":
								s_url = "/system/shared/collection/icons/16x16/plain/jpg.png";
								break;
							case "jpeg":
								s_url = "/system/shared/collection/icons/16x16/plain/jpg.png";
								break;
							case "pdf":
								s_url = "/system/shared/collection/icons/16x16/plain/pdf.png";
								break;
							case "png":
								s_url = "/system/shared/collection/icons/16x16/plain/png.png";
								break;
							case "ppt":
								s_url = "/system/shared/collection/icons/16x16/plain/ppt.png";
								break;
							case "tif":
								s_url = "/system/shared/collection/icons/16x16/plain/tif.png";
								break;
							case "xls":
								s_url = "/system/shared/collection/icons/16x16/plain/xls.png";
								break;
							case "xlsx":
								s_url = "/system/shared/collection/icons/16x16/plain/xls.png";
								break;
							case "xml":
								s_url = "/system/shared/collection/icons/16x16/plain/xml.png";
								break;
							default:
								s_url = "/system/shared/collection/icons/16x16/plain/document_empty.png";
								break;
						}

						s_icon = "<img src=\"" + s_url + "\"/>";

						return s_icon;
					},
					width: 40
				},
				{
					header: "Name",
					dataIndex: "text",
					flex: 2,
					menuDisabled: true,
					sortable: false
				},
				{
					header: "Changed",
					dataIndex: "mtime",
					width: 68
				},
				{
					header: "Size (kb)",
					dataIndex: "size",
					align: "right",
					width: 66
				}
			],
			listeners: {
				itemkeyup: {
					fn: function(i_view, i_selected, i_element, n_index, i_event) {

						var i_grid = i_view.grid;
						var i_store = i_grid.getStore();
						var a_records = i_store.getRange();
						var i_newSelect;
						var n_prev;

						var s_key = String.fromCharCode(i_event.keyCode).toLowerCase();

						if (i_event.getKey() != i_event.ENTER) {

							Ext.Array.each(a_records, function(i_record) {

								var s_text = i_record.get("text") || "";
								s_text = s_text.toLowerCase();

								if (Ext.String.startsWith(s_text, s_key)) {

									var n_current = i_store.find("text", i_record.get("text"));

									if (Ext.isEmpty(n_prev)) {
										if (n_current < n_index) {
											n_prev = n_current;
										}
									}

									if (n_current > n_index) {
										i_newSelect = i_record;
										return false;
									}
								}
							});

							if (!i_newSelect && !Ext.isEmpty(n_prev)) {
								i_newSelect = i_store.getAt(n_prev);
							}
							if (i_newSelect) {
								i_view.select(i_newSelect);
								i_view.focusNode(i_newSelect, 20);
							}
						}
						else {
							i_grid.fireEvent("itemdblclick", i_view, i_selected, i_element, n_index, i_event);
						}
					}
				},
				select: {
					fn: function(i_view, i_record) {

						var s_extension = i_record.get("ext");

						var i_panel = i_self.getFormPanel();
						var i_form = i_panel.getForm();

						if (s_extension != "folder") {
							i_self.fireEvent("fileselect", i_self, i_record);
						}
						else {
							i_form.setValues({
								filename: ""
							});
						}
					}
				},
				itemdblclick: {
					fn: function(i_view, i_record, i_element, n_index, i_event) {

						i_event.preventDefault();

						var s_extension = i_record.get("ext");

						var i_formpanel = i_self.getFormPanel();
						var o_values = i_formpanel.getValues();

						if (s_extension == "folder") {

							i_self.fireEvent("folderselect", i_self, i_record);

							var i_grid = i_view.grid;
							var i_store = i_grid.getStore();

							i_store.load();
						}
						else {
							var a_path = [];

							a_path.push(o_values.path);
							a_path.push(o_values.filename);

							var s_file = ip2.cleanPath(a_path.join("/"));

							i_self.fireEvent("fileopen", i_self, s_file);

							i_self.close();
						}
					}
				}
			}
		});

		i_self.setObjectGrid(i_grid);

		return i_grid;
	},

	getPathToSelected: function() {

		var i_self = this;

		var s_path = i_self.getPath();

		var i_navigator = i_self.getNavigator();
		var i_selected = i_navigator.getSelection()[0];

		var a_path = [];

		if (!i_selected.isRoot()) {

			var i_current = i_selected;

			while (!i_current.isRoot()) {

				a_path.unshift(i_current.get("text"));
				i_current = i_current.parentNode;
			};

			a_path.unshift(s_path);
		}

		s_path = a_path.join("/");

		s_path = ip2.cleanPath(s_path);

		return s_path;
	}
});
