Ext.define("Ext.ux.form.field.UploadPicker", {

	extend: "Ext.form.field.ComboBox",

	alias: ["widget.uploadpicker"],

	triggers: {
		clear: {
			cls: Ext.baseCSSPrefix + "form-clear-trigger",
			weight: 1,
			handler: "onClearClick",
			hidden: true,
			scope: "this"
		},
		upload: {
			cls: "x-ux-form-trigger-upload",
			tooltip: ip2.i18n({
				da: "Upload en fil",
				en: "Upload a file"
			}),
			weight: 3,
			scope: "this"
		},
		picker: {
			weight: 2,
			handler: "onTriggerClick",
			scope: "this"
		},
	},

	pageSize: 6,
	displayField: "path",
	valueField: "path",
	typeAhead: true,
	minChars: 4,
	enableKeyEvents: true,
	queryParam: "search",
	queryMode: "remote",
	lastQuery: "",
	triggerAction: "all",

	config: {
		invalidText: ip2.i18n({
			da: "Filen skal af typen $extensions",
			en: "The file must be in $extensions format"
		}),
		needLoad: true,
		fileuploadForm: null,
		uploadOnly: false,
		uploadText: ip2.i18n({
			da: "Uploader fil to server",
			en: "Uploading file to server"
		}),
		path: "/",
		extensions: "gif,png,jpg,jpeg,bmp",
		ignoreStaticDir: false,
		browseService: "/ip2-services/webbios.aspx?pathList=",
		uploadService: "/ip2-services/webbios.aspx?action=movestmf&path=",
		convertFromPdf: false,
		uploadActions: [],
		image: "",
		scaling: null
	},

	listeners: {
		afterrender: {
			fn: function (i_field) {
				var value = i_field.getValue();
				if (i_field.inputEl) {


					if (Ext.isEmpty(value)) {
						i_field.getTrigger("clear").hide();
					}
					else {
						i_field.getTrigger("clear").show();
					}

					if (i_field.readOnly) {
						i_field.getTrigger("clear").hide();
					}
				}
			},
			single: true
		},
		change: {
			fn: function (i_field, value) {
				if (i_field.inputEl) {

					var a_values = Ext.Array.from(value);

					if (a_values.length === 0) {
						i_field.allQuery = "";
						i_field.clearValue();
						i_field.getTrigger("clear").hide();
					}
					else {
						i_field.allQuery = i_field.lastQuery;
						if (!i_field.readOnly) {
							i_field.getTrigger("clear").show();
						}
					}
				}
			}
		},
		enable: {
			fn: function (i_field) {

				var s_value = i_field.getValue();

				i_field.getTrigger("clear")[s_value ? "show" : "hide"]();
			},
			buffer: 10
		},
		disable: {
			fn: function (i_field) {
				i_field.getTrigger("clear").hide();
			},
			buffer: 10
		},
		writeablechange: {
			fn: function (i_field, b_readOnly) {

				i_field.getTrigger("clear")[b_readOnly ? "hide" : "show"]();


			},
			buffer: 10
		},
		uploadComplete: {
			fn: function(i_self, a_files) {

				var b_converFromPdf = i_self.getConvertFromPdf();
				var a_actions = i_self.getUploadActions() || [];

				var s_url = a_files[0];

				if (b_converFromPdf) {

					i_self.doConvert(a_files, function(o_result) {

						if (o_result && o_result.destination) {

							if (s_url != o_result.destination) {
								s_url = o_result.destination;

								i_self.setValue(s_url);
							}
						}

						i_self.doUploadActions(s_url);
					});
				}
				else {
					i_self.doUploadActions(s_url);
				}
			}
		}
	},

	initComponent: function () {

		var i_self = this;
		var o_initial = Ext.apply({}, i_self.initialConfig);

		// Overload the extensions config to a comma seperated list if array was supplied
		if (o_initial.extensions && Ext.isArray(o_initial.extensions)) {
			o_initial.extensions = o_initial.extensions.join(",");
		}

		Ext.apply(i_self, {
			extensions: o_initial.extensions || i_self.extensions,
			invalidText: o_initial.invalidText || i_self.invalidText,
			path: o_initial.path || i_self.path,
			pageSize: o_initial.pageSize || i_self.pageSize,
			browseService: o_initial.browseService || i_self.browseService,
			uploadService: o_initial.uploadService || i_self.uploadService,
			ignoreStaticDir: o_initial.ignoreStaticDir || i_self.ignoreStaticDir
		});

		// Lets make sure our services have static dir set for each if using own
		var s_preset = ip2.preset.staticPath || "pp-static";
		var b_ignoreStaticDir = i_self.ignoreStaticDir;

		if (i_self.browseService != o_initial.browseService) {

			if (i_self.path.indexOf(s_preset) == -1 && !b_ignoreStaticDir) {
				i_self.path = [s_preset, i_self.path].join("/");
				i_self.path = ip2.cleanPath(i_self.path);
			}

			i_self.browseService += i_self.path;
		}

		if (i_self.uploadService != o_initial.uploadService) {

			if (i_self.path.indexOf(s_preset) == -1 && !b_ignoreStaticDir) {
				i_self.path = [s_preset, i_self.path].join("/");
				i_self.path = ip2.cleanPath(i_self.path);
			}

			i_self.uploadService += i_self.path;

			i_self.uploadService += "&ignorestaticdir=true";
		}

		//console.log(i_self.uploadService, i_self.browseService);

		i_self.createStore();

		// Setup validation and invalid text
		(function () {

			// Create the invalid text
			i_self.invalidText = ip2.microTemplate(i_self.invalidText, {
				extensions: i_self.extensions
			});

			var s_vtypeKey = ip2.unique("ExtendedImageValidation", "");
			var o_config = {};

			o_config[s_vtypeKey] = function (value) {

				var a_extensions = i_self.extensions.split(",");
				if (a_extensions.length > 0) {
					if (a_extensions.indexOf("*") == -1) {
						var r_extensions = new RegExp("^.*\.(" + a_extensions.join("|") + ")$");
						return r_extensions.test(value.toLowerCase());
					}
					return true;
				}
				else {
					return false;
				}
			};
			o_config[s_vtypeKey + "Text"] = i_self.invalidText;

			Ext.apply(Ext.form.VTypes, o_config);

			Ext.apply(i_self, {
				vtype: s_vtypeKey,
				vtypeKey: s_vtypeKey
			});
		})();

		if (i_self.uploadOnly) {
			i_self.editable = false;
			i_self.typeAhead = false;
		}

		i_self.callParent(arguments);

		i_self.on({
			afterrender: {
				fn: function() {
					i_self.onAfterrender();
				},
				single: true
			},
			keydown: {
				fn: function(item, event) {
					if (event.ctrlKey && (event.keyCode == 90 || event.keyCode == 82 || event.keyCode == 89)) {
						if (i_self.isValid()) {
							i_self.needLoad = false;
							if (i_self.isExpanded) {
								i_self.collapse();
							}
						}
					}
				}
			},
			paste: {
				element: "inputEl",
				fn: function(event, inputEl) {
					if (i_self.isValid()) {
						i_self.needLoad = false;
						if (i_self.isExpanded) {
							i_self.collapse();
						}
					}
				}
			},
			beforequery: {
				fn: function() {
					var value = i_self.getValue();
					if (value) {
						var b_isUrl = i_self.isURL(value);
						if (b_isUrl) {
							i_self.setImage(value);
							return false;
						}
						else {
							if (!i_self.needLoad) {
								i_self.needLoad = true;
								return false;
							}
						}
					}
				}
			},
			change: {
				fn: function(item, value) {

					if (!value) {
						i_self.allQuery = "";
						i_self.setImage(value);
					}
					else {
						if (i_self.isValid()) {
							var b_isUrl = i_self.isURL(value);
							if (b_isUrl) {
								if (i_self.isExpanded) {
									i_self.collapse();
								}
							}
							var s_value = "";
							if (Ext.isNumber(value)) {
								s_value = i_self.getDisplayValue();
							}
							else {
								s_value = value;
							}
							i_self.setImage(value);
							i_self.setImage(value);
							i_self.allQuery = i_self.lastQuery;
						}
						else {
							i_self.allQuery = value;
							i_self.setImage(value);
						}
					}
				}
			},
			enable: {
				fn: function(i_field) {

					if (i_field.uploadOnly) {

						setTimeout(function() {
							i_field.setReadOnly(true);
							var o_triggers = i_field.getTriggers();
							o_triggers.picker.hide();
							o_triggers.upload.show();
						}, 10);
					}
				}
			}
		});

		return i_self;
	},

	onExpand: function() {
		var i_self = this;
		i_self.ignoreSelection++;
		i_self.callParent(arguments);
	},

	isURL: function(value) {
		var s_value = String(value);
		var r_http = /^(ftps?|https?):\/\//;
		return r_http.test(s_value);
	},

	initValue: function () {

		var i_self = this;

		if (!i_self.value) {
			i_self.value = i_self.lastValue = i_self.originalValue = i_self.getRawValue();
		}
		else {
			i_self.lastValue = i_self.originalValue = i_self.value;
		}

		return i_self;
	},

	isDirty: function () {

		var i_self = this;

		var i_selectedRecord = i_self.getSelectedRecord();

		var s_value = i_selectedRecord ? i_selectedRecord.get(i_self.valueField) : i_self.getValue() || i_self.getRawValue();

		var s_original = i_self.originalValue;

		return s_value != s_original;
	},

	onHandelChange: function(i_field, value) {


		var i_self = this;
		var i_el = i_self.bodyEl;
		var s_uploadText = i_self.uploadText;
		var s_vtypeKey = i_self.vtypeKey;
		var s_path = ip2.cleanPath(i_self.path) + "/";
		var i_fileField = i_self.getFileuploadField();

		var s_value = i_fileField.getValue();
		var b_allowed = Ext.form.VTypes[s_vtypeKey](s_value);
		var i_trigger_el = i_self.triggerEl.elements[1];

		i_field.isHandling = true;

		if (!s_value) {
			i_self.clearInvalid();
		}

		if (!b_allowed) {
			ip2.messageBox({
				icon: Ext.Msg.ERROR,
				title: ip2.i18n({
					da: "<b>Fejl</b>",
					en: "<b>Error</b>"
				}),
				message: i_self.invalidText,
				closable: false,
				yesText: ip2.i18n({
					da: "Ok",
					en: "OK"
				}),
				yesFn: function () {
					i_field.isHandling = false;
				},
				cancelFn: function() {
					i_field.isHandling = false;
				}
			});
		}
		else {
			var a_files = i_field.fileInputEl.dom.files;
			var msg = ip2.i18n({
				da: "Kontrolerer fil....",
				en: "Checking file..."
			});
			i_self.disable();
			i_el.mask(msg);

			Ext.ux.file.util.Handler.checkFiles(s_path, a_result, function (o_result) {

				var a_update = o_result.update;
				var a_create = o_result.create;

				var b_update = false;
				var b_create = false;
				var b_cancel = false;

				if (a_update.length > 0) {
					b_update = true;
					s_path = ip2.cleanPath(i_self.path) + "/";
					Ext.ux.file.util.Handler.getUIConflickWindow(i_trigger_el,
						i_self,
						s_path,
						a_update,
						function (cancel, a_override, a_rename) {
							b_cancel = cancel;
							if (a_override.length !== 0 || a_rename.length !== 0) {
								var o_record;
								var msg = "";
								var b_rename = false;
								if (a_rename.length > 0) {
									b_rename = true;
									o_record = a_rename[0];
									msg = s_uploadText;
								}
								else {
									msg = ip2.i18n({
										da: "Overskriver fil....",
										en: "Overwriting file..."
									});
									o_record = a_override[0];
								}

								i_el.mask(msg);

								var s_uploadpath = i_self.path;
								var s_name = b_rename === true ? o_record.suggestedName : o_file.name;
								var s_url = ip2.cleanPath([i_self.path, s_name].join("/"));
								if (Ext.ux.file.util.Handler.hasFileManager()) {
									Ext.ux.file.util.Handler.createRecords(s_uploadpath, [o_record], b_rename, function () {
										if (!b_create) {
											i_el.unmask();
											i_self.enable();
											i_self.setValue(s_url);
											i_field.isHandling = false;
											i_self.fireEvent("uploadComplete", i_self, [s_url]);
										}
										else {
											i_el.mask(s_uploadText);
										}
									});
								}
								else {
									Ext.ux.file.util.Handler.uploadFiles(s_uploadpath, [o_record], b_rename, function () {
										if (!b_create) {
											i_el.unmask();
											i_self.enable();
											i_self.setValue(s_url);
											i_field.isHandling = false;
											i_self.fireEvent("uploadComplete", i_self, [s_url]);
										}
										else {
											i_el.mask(s_uploadText);
										}
									});
								}
							}
							else {
								if (!b_create) {
									i_el.unmask();
									i_self.clearInvalid();
									i_self.enable();
									i_field.isHandling = false;
								}
							}
						}, false);
				}
				if (a_create.length > 0) {
					b_create = true;
					if (!b_update) {
						i_el.mask(s_uploadText);
					}

					var s_uploadpath = i_self.path;
					var s_url = ip2.cleanPath([i_self.path, o_file.name].join("/"));
					if (Ext.ux.file.util.Handler.hasFileManager()) {
						Ext.ux.file.util.Handler.createRecords(s_uploadpath, [o_file], false, function () {
							if (!b_update || b_cancel) {
								i_el.unmask();
								i_self.enable();
								i_self.setValue(s_url);
								i_field.isHandling = false;
								i_self.fireEvent("uploadComplete", i_self, [s_url]);
							}
						});
					}
					else {
						Ext.ux.file.util.Handler.uploadFiles(s_uploadpath, [o_file], false, function () {
							if (!b_update || b_cancel) {
								i_el.unmask();
								i_self.enable();
								i_self.setValue(s_url);
								i_field.isHandling = false;
								i_self.fireEvent("uploadComplete", i_self, [s_url]);
							}
						});
					}
				}
			});


		}
		i_field.reset();
	},

	addFormControls: function () {

		var i_self = this;
		var i_fileField = i_self.getFileuploadField();

		i_fileField.on({
			change: {
				fn: function (i_field, value) {
					if (!i_field.isHandling) {
						i_self.onHandelChange(i_field, value);
					}
				}
			}
		});
	},

	createStore: function () {

		var i_self = this;

		i_self.store = Ext.create("Ext.data.Store", {
			fields: ["name", "path"],
			autoLoad: false,
			pageSize: 6,
			proxy: {
				type: "ajax",
				url: i_self.browseService,
				reader: {
					type: "json",
					rootProperty: "rows",
					totalProperty: "totalRows"
				},
				extraParams: {
					func: "listDirByExtension",
					extnList: i_self.extensions,
					metaData: true,
					sort: true
				}
			}
		});
		var i_store = i_self.store;
		i_store.load();

		return i_self;
	},

	getTemplate: function() {

		var i_self = this;

		var i_tpl = Ext.create("Ext.XTemplate",
			"<tpl for=\".\">",
				"<span style=\"",
					"width: 43px;",
					"height: 37px;",
					"background-image: url({[this.getUrl(values.path)]});",
					"background-size: 35px;",
					"background-position: 50% 50%;",
					"background-repeat: no-repeat;",
					"display: inline-block;",
				"\"></span>",
				"<span style=\"",
					"height: 45px;",
					"position: relative;",
					"top: -13px;",
					"padding-left: 10px;",
				"\">{name}</span>",
			"</tpl>",
			{
				getUrl: function(s_value) {

					var a_value = s_value.split(".");
					var s_extensions = a_value.pop().toLowerCase();

					if (Ext.ux.file.util.Handler.imageExtension.indexOf(s_extensions) == -1) {
						return Ext.ux.file.util.Handler.getUrlByExtension(s_value);
					}

					s_value = "/ip2-services/scaleImage.aspx?".concat(
						Ext.Object.toQueryString({
							width: 43,
							height: 37,
							path: s_value,
							padCanvas: false,
							_dc: ip2.getDcTimestamp()
						})
					);

					return s_value;
				}
			}
		);
		return i_tpl;
	},

	createPicker: function() {

		var i_self = this;
		var i_picker;

		var o_options = Ext.apply({
			xtype: "boundlist",
			pickerField: i_self,
			selectionModel: i_self.pickerSelectionModel,
			floating: true,
			hidden: true,
			store: i_self.store,
			preserveScrollOnRefresh: true,
			pageSize: 6,
			tpl: i_self.tpl,
			itemTpl: i_self.getTemplate(),
			createPagingToolbar: function() {
				var i_toolbar = Ext.widget("pagingtoolbar", {
					itemId: "pagingToolbar",
					pageSearch: false,
					pageSizeEdit: false,
					store: i_self.store,
					border: false,
					displayInfo: true
				});

				i_self._toolbar = i_toolbar;

				return i_toolbar;
			}
		}, i_self.listConfig, i_self.defaultListConfig);

		i_picker = i_self.picker = Ext.widget(o_options);

		if (i_self.pageSize) {
			i_picker.pagingToolbar.on("beforechange", i_self.onPageChange, i_self);
		}

		if (!i_picker.initialConfig.maxHeight) {
			i_picker.on({
				beforeshow: i_self.onBeforePickerShow,
				scope: i_self
			});
		}

		i_picker.getSelectionModel().on({
			beforeselect: i_self.onBeforeSelect,
			beforedeselect: i_self.onBeforeDeselect,
			scope: i_self
		});

		return i_picker;
	},

	onAfterrender: function () {

		var i_self = this;
		var s_icon = i_self.getValue();
		var i_el = i_self.getEl();
		var i_input = i_self.inputEl;
		var o_triggers = i_self.getTriggers();

		// Create the fake form to handle uploads
		var i_form = Ext.widget("form", {
			itemId: "fileuploadform",
			renderTo: Ext.getBody(),
			border: false,
			hidden: true,
			items: [
				{
					xtype: "fileuploadfield",
					itemId: "fileuploadfield",
					buttonOnly: true,
					listeners: {
						afterrender: {
							fn: function (i_field) {

								i_self.fileuploadForm = i_field.up("#fileuploadform");
								i_self.addFormControls();
								i_self.fileuploadForm.getEl().insertAfter(i_el);

								var i_uploadDomEl = i_self.getTrigger("upload").getEl();

								i_uploadDomEl.addListener("click", function() {

									i_self.isUploading = true;

									var i_field = i_self.getFileuploadField();
									var i_inputEl = i_field.fileInputEl;
									var i_inputElDom = i_inputEl.dom;

									i_inputElDom.click.apply(i_inputElDom);

									setTimeout(function() {
										i_self.isUploading = false;
									}, 100);
								});
							}
						}
					}
				}
			]
		});

		if (s_icon && Ext.isString(s_icon)) {
			i_self.setImage(s_icon);
		}

		if (i_self.uploadOnly) {
			i_self.setReadOnly(true);
			o_triggers.upload.show();
		}

		// var i_dropzone = Ext.widget("ux.grid.dropzone", {
		// 	renderTo: Ext.getBody(),
		// 	wrapper: i_self.inputWrap,
		// 	zones: [{
		// 		path: i_self.path,
		// 		title: "",
		// 		maxItems: 1
		// 	}],
		// 	style: {
		// 		"position": "absolute",
		// 		"padding": "5px",
		// 		"font-size": "5px",
		// 		"border": "1px solid black"
		// 	},
		// 	dropFn: function(s_value, o_drop) {

		// 		if (s_value) {

		// 			i_self.setValue(s_value);
		// 		}
		// 	}
		// });

		// i_dropzone.getEl().insertBefore(i_self.inputWrap);

		return i_self;
	},

	onPageChange: function(toolbar, newPage) {

		this.loadPage(newPage, {
			rawQuery: true
		});
		return false;
	},

	onBindStore: function(store, initial) {
		this.callParent(arguments);
		this.pickerSelectionModel.deselectOnContainerClick = false;
	},

	setValue: function(value) {

		var i_self = this;
		i_self.callParent(arguments);
		if (value && Ext.isString(value)) {
			i_self.setImage(value);
		}

		if (i_self.uploadOnly) {
			var o_triggers = i_self.getTriggers();
			i_self.setReadOnly(true);
			o_triggers.upload.show();
		}
	},

	onDestroy: function () {

		var i_self = this;
		var i_form = i_self.getFileuploadForm();

		i_form && i_form.destroy();

		i_self.callParent();
	},

	getFileuploadField: function () {

		var i_self = this;
		var i_form = i_self.getFileuploadForm();

		return i_form.down("#fileuploadfield");
	},

	doCrop: function(a_files) {

		Ext.Array.each(a_files, function(s_url) {
			Ext.Ajax.request({
				method: "POST",
				url: "/ip2-services/ip2transaction.aspx",
				jsonData: {
					action: "imageUtl.image_cropTiles",
					image: s_url
				},
				success: function(o_response) {},
				faliure: function(o_err) {}
			});
		});
	},

	doUploadActions: function(s_url) {

		var i_self = this;

		var a_actions = i_self.getUploadActions() || [];

		Ext.Array.each(a_actions, function(o_config) {

			var o_parms = o_config.params || {};
			var s_path = o_config.path;

			if (o_parms.hasOwnProperty("media")) {
				o_parms.media = s_url;
			}
			else {
				o_parms.image = s_url;
			}

			Ext.Ajax.request({
				method: "POST",
				url: s_path,
				jsonData: o_parms,
				success: function(o_response) {
				},
				faliure: function(o_err) {
				}
			});
		});
	},

	doConvert: function(a_files, f_callback) {

		var i_self = this;
		var i_el = i_self.bodyEl;

		i_el.mask(ip2.i18n({
			da: "Konverterer...",
			en: "Converting...."
		}));

		Ext.Array.each(a_files, function(s_url) {
			Ext.Ajax.request({
				method: "POST",
				url: "/ip2-services/ip2transaction.aspx",
				jsonData: {
					action: "pdfutils.createThumbnail",
					path: s_url
				},
				success: function(o_response) {

					i_el.unmask();

					var o_result = Ext.decode(o_response.responseText, true) || {
						success: false
					};

					if (o_result.success) {
						f_callback(o_result);
					}
					else {
						f_callback(null);
					}
				},
				failure: function(o_err) {

					var o_result = Ext.decode(o_err.responseText, true) || {
						success: false,
						message: "Server error"
					};

					i_el.unmask();

					var i_template = Ext.create("Ext.XTemplate",
						"<tpl>",
							"<p><strong>Error {msgid}</strong><p>",
							"<p>Message <i>{text}</i></p>",
						"</tpl>"
					);

					i_template.compile();

					ip2.messageBox({
						icon: Ext.Msg.ERROR,
						title: ip2.i18n({
							da: "<b>" + o_err.statusText + "</b>",
							en: "<b>" + o_err.statusText + "</b>"
						}),
						message: i_template.apply(o_result),
						closable: false,
						yesText: ip2.i18n({
							da: "Ok",
							en: "OK"
						}),
						yesFn: function () {
							f_callback(null);
						}
					});
				}
			});
		});
	},

	onClearClick: function () {

		var i_self = this;

		i_self.clearValue();

		return i_self;
	},

	getValue: function() {

		var i_self = this;

		var value = i_self.callOverridden(arguments);

		if (!value) {
			var i_selectedRecord = i_self.getSelectedRecord();

			value = i_selectedRecord ? i_selectedRecord.get(i_self.valueField) : i_self.getRawValue();
		}

		return value;
	},

	updateImage: function(s_value) {

		var i_self = this;
		var i_inputEl = i_self.inputEl;
		var i_inputWrap = i_self.inputWrap;
		var i_imageEl;

		if (s_value && i_inputEl) {

			i_inputEl.setStyle("padding-left", "50px");

			i_imageEl = i_inputWrap.down("span");

			if (!i_imageEl) {

				var i_template = Ext.create("Ext.XTemplate",
					"<span ",
					 "style=\"",
						"position: absolute;",
						"top: 4px;",
						"left: 10px;",
						"background-image: url({url});",
						"background-size: contain;",
						"background-position: center;",
						"height: 30px;",
						"width: 35px;",
						"background-repeat: no-repeat",
					"\"></span>"
				);

				var s_html = i_template.apply({
					url: s_value
				});

				i_inputWrap.insertFirst(Ext.DomHelper.createDom(s_html))

			}
			else {
				i_imageEl.show();
				i_imageEl.setStyle("background-image", "url(" + s_value + ")")
			}
		}
		else {
			if (i_inputEl) {
				i_inputEl.setStyle("padding-left", "5px");
			}
			if (i_inputWrap) {
				i_imageEl = i_inputWrap.down("span");

				if (i_imageEl) {
					i_imageEl.hide();
				}
			}
		}
	}
});
