Ext.define("Ext.ux.form.field.UploadPickerManager", {
	extend: "Ext.ux.form.field.UploadPicker",
	alias: "widget.uploadpickermanager",

	triggers: {
		picker: {
			weight: 1,
			handler: 'onTriggerClick',
			scope: 'this'
		},
		search: {
			cls: 'x-ux-form-trigger-search',
			weight: 2,
			tooltip: ip2.i18n({
				da: "Søg i filmanager",
				en: "Search in file manager"
			}),
			handler: "onTrigger2Click",
			scope: "this"
		},
		upload: {
			cls: 'x-ux-form-trigger-upload',
			tooltip: ip2.i18n({
				da: "Upload en fil",
				en: "Upload a file"
			}),
			weight: 3,
			scope: "this"
		}
	},

	displayField: "FILNAME",

	valueField: "FILFILTKN",

	minChars: 1,

	typeAhead: true,

	typeAheadDelay: 250,

	queryDelay: 1000,

	loadCount: 0,

	record: undefined,

	submitRaw: false,

	initComponent: function() {
		var i_self = this;
		i_self.displayTpl = Ext.create("Ext.XTemplate",
			'<tpl for=".">',
				'<tpl if="this.checkBlank(values.FILFILTKN, values.FILNAME) == true">',
					'',
				'</tpl>',
				'<tpl if="this.checkBlank(values.FILFILTKN, values.FILNAME) == false">',
					'<tpl if="values.FILEXTERNAL == true">',
						'{FILORIPATH}',
					'</tpl>',
					'<tpl if="values.FILEXTERNAL == false">',
						'{FILPATH}{FILNAME}',
					'</tpl>',
				'</tpl>',
			'</tpl>',
			{
				checkBlank: function(FILFILTKN, FILNAME) {
					if (FILFILTKN && FILNAME) {
						return false;
					}
					return true;
				}
			}
		);
		i_self.callParent(arguments);
		if (i_self.saveUrl == undefined) {
			var s_path = ip2.cleanPath(i_self.path) + "/";
			var o_hive = Ext.ux.file.util.Handler.getHiveByPath(s_path);
			i_self.saveUrl = o_hive.saveUrl;
		}
		i_self.createStore();

		i_self.on({
			afterrender: {
				fn: function(item) {
					item.createDropzone();
				}
			}
		});

		return i_self;
	},

	getTemplate: function() {
		var i_self = this;
		var i_tpl = Ext.create("Ext.XTemplate",
			'<tpl for=".">',
				'<tpl if="this.isExternal({FILEXTERNAL}) == true">',
					'<span style="',
						'width: 43px;',
						'height: 37px;',
						'background-image: url({[this.getExtension(values.FILORIPATH)]});',
						'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;',
					'">{FILORIPATH} (' + ip2.i18n({ da: "ekstern", en: "external" }) + ')</span>',
				'</tpl>',
				'<tpl if="this.isExternal({FILEXTERNAL}) == false">',
					'<span style="',
						'width: 43px;',
						'height: 37px;',
						'background-image: url({[this.getExtension(values.FILPATH + values.FILNAME)]});',
						'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;',
					'">{FILPATH}{FILNAME}</span>',
				'</tpl>',
			'</tpl>',
			{
				isExternal: function(o_value) {
					var b_isExternal = o_value.FILEXTERNAL;
					return b_isExternal ? true : false;
				}
			},
			{
				getExtension: function(path) {
					var s_value = path;
					var a_value = s_value.split(".");
					var s_extensions = a_value.pop();
					if (Ext.ux.file.util.Handler.imageExtension.indexOf(s_extensions) == -1) {
						return Ext.ux.file.util.Handler.getUrlByExtension(path);
					}
					return "'" + path + "'";
				}
			}
		);
		return i_tpl;
	},

	doSave: function(f_callback) {
		var i_self = this;
		var s_raw = i_self.getRawValue();
		if (i_self.submitRaw) {
			return s_raw;
		}
		var s_value = Number(i_self.getSubmitValue());
		var s_path = ip2.cleanPath(i_self.path) + "/";
		if (Ext.isNumber(s_value)) {
			f_callback(true);
		}
		else {
			var b_isUrl = i_self.isURL(s_raw);
			if (b_isUrl) {
				var s_name = s_raw.split("/").pop();
				var a_files = [s_name];
				Ext.ux.file.util.Handler.getRecordsByName(s_path, a_files, function(a_records) {

					if (a_records.length > 0) {
						var a_conflict = [{
							name: s_name,
							src: s_raw,
							http: a_records[0].data.FILORIPATH,
							external: a_records[0].data.FILEXTERNAL
						}];

						var i_windowConflick = Ext.widget("fileconflict", {
							files: a_conflict,
							path: s_path,
							width: 900,
							height: 600,
							okFn: function(a_override, a_rename) {
								if (a_override.length > 0) {
									if (i_self.saveUrl) {
										Ext.ux.file.util.Handler.curlFileFromURL(s_path, s_raw, function() {
											a_records[0].set("FILORIPATH", s_raw);
											Ext.ux.file.util.Handler.upsertRecords(a_records, function(a_records) {
												i_self.setValue(a_records);
												f_callback(true);
											});
										});
									}
									else {
										a_records[0].set("FILORIPATH", s_raw);
										Ext.ux.file.util.Handler.upsertRecords(a_records, function(a_records) {
											i_self.setValue(a_records);
											f_callback(true);
										});
									}
								}
								if (a_rename.length > 0) {
									if (i_self.saveUrl) {
										var s_name = a_rename[0].suggestedName;
										Ext.ux.file.util.Handler.createRecordByUrlWithName(s_path, s_raw, s_name, function(a_records) {
											i_self.setValue(a_records);
											f_callback(true);
										});
									}
									else {
										var a_file = [{
											name: a_rename[0].suggestedName,
											size: 0,
											external: true
										}];
										Ext.ux.file.util.Handler.createRecordsNoUploadNoImageInfo(s_path, a_file, function(a_records) {
											var o_record = a_records[0];
											o_record.set("FILFILTKN", 0);
											o_record.set("FILORIPATH", s_raw);
											Ext.ux.file.util.Handler.upsertRecords(a_records, function(a_records) {
												i_self.setValue(a_records);
												f_callback(true);
											});
										});
									}
								}
								if (a_override.length == 0 && a_rename.length == 0) {
									f_callback(false);
								}
							},
							cancelFn: function() {
								f_callback(false);
							}
						});

						i_windowConflick.show();
					}
					else {
						if (i_self.saveUrl) {
							Ext.ux.file.util.Handler.createRecordByUrl(s_path, s_raw, function(a_records) {
								i_self.setValue(a_records);
								f_callback(true);
							});
						}
						else {
							var a_file = [{
								name: s_name,
								size: 0,
								external: true
							}];
							Ext.ux.file.util.Handler.createRecordsNoUploadNoImageInfo(s_path, a_file, function(a_records) {
								var o_record = a_records[0];
								o_record.set("FILFILTKN", 0);
								o_record.set("FILORIPATH", s_raw);
								Ext.ux.file.util.Handler.upsertRecords(a_records, function(a_records) {
									i_self.setValue(a_records);
									f_callback(true);
								});
							});
						}
					}
				});
			}
			else {
				var a_raw = s_raw.split("/");
				var s_name = a_raw.pop();
				var s_path = a_raw.join("/") + "/";
				Ext.ux.file.util.Handler.getRecordByName(s_path, s_name, function(a_records) {
					if (a_records.length == 0) {
						f_callback(false);
						var s_title = ip2.i18n({
							da: "Fejl",
							en: "Error"
						});
						var s_msg = ip2.i18n({
							da: "Ingen fil fundet, vælg en anden",
							en: "No fil found, please choosen another"
						});

						Ext.Msg.show({
							title: s_title,
							msg: s_msg,
							buttons: Ext.Msg.OK,
							icon: Ext.Msg.ERROR
						});
					}
					else {
						var o_record = a_records[0];
						i_self.setValue(o_record);
						f_callback(true);
					}
				});
			}
		}
	},

	onTrigger2Click: function() {
		var i_self = this;
		var a_triggers = i_self.triggerEl.elements;
		var el = a_triggers[1];
		var s_path = ip2.cleanPath(i_self.path) + "/";
		var wnd = Ext.widget("filesearch", {
			animateTarget: el,
			path: s_path,
			okFn: function(o_record) {
				i_self.setValue([o_record]);
			}
		});

		wnd.show();
	},

	createStore: function () {

		var i_self = this;
		var s_path = ip2.cleanPath(i_self.path) + "/";
		var i_store = Ext.create('Ext.data.Store', {
			model: ip2.model({
				dmd: "dmd/webshop.dmd",
				entityName: "WSHFILET00",
				context: 'grid',
				uiName: "portfolio"
			}),
			autoLoad: false,
			pageSize: i_self.pageSize,
			proxy: {
				type: 'ajax',
				url: '/ip2-Services/ip2dmdproxy.aspx',
				reader: {
					type: 'json',
					rootProperty: 'rows',
					totalProperty: 'totalRows'
				},
				extraParams: {
					dmdFile: 'dmd/webshop.dmd',
					model: "WSHFILET00",
					context: "grid",
					uiName: "portfolio",
					action: "getRows",
					sort: "FILFILTKN",
					dir: "asc",
					where: "FILPATH = '" + s_path + "'"
				}
			}
		});

		i_store.load();

		i_self.store = i_store;

		return i_self;
	},

	createDropzone: function() {
		var i_self = this;
		var s_path = ip2.cleanPath(i_self.path) + "/";
		var el = i_self.inputEl;

		var o_dropbox = Ext.widget("gallerydropbox", {
			flex: 1,
			dropText: ip2.i18n({ da: "Drop for at tilføje file", en: "Drop to add file" }),
			path: s_path,
			extensions: Ext.isDefined(i_self.extensions) ? i_self.extensions : Ext.ux.file.util.Handler.extensions,
			maxItems: 1,
			style: {
				"position": "absolute",
				"padding": "5px",
				"top": "0px",
				"left": "0px",
				"right": "0px",
				"bottom": "0px",
				"font-size": "25px"
			},
			listeners: {
				bodydragenter: function(i_dropbox, o_event) {
					if (i_self.inputEl) {
						var inputWidth = i_self.inputEl.getWidth();
						var dropzoneWidth = i_self.dropzone.el.getWidth();
						if (dropzoneWidth != inputWidth) {
							i_self.dropzone.setWidth(inputWidth);

							var i_dropzone = i_self.dropzone;

							var f_layout = i_dropzone.doLayout || i_dropzone.updateLayout;

							f_layout.call(i_dropzone);
						}

						i_self.dropzone.getEl().setStyle("display", "inline");
						i_self.dropzone.getEl().setStyle("opacity", "0.7");
					}
				},
				bodydragleave: function(i_dropbox, o_event) {
					i_self.dropzone.getEl().setStyle("display", "none");
					i_self.dropzone.getEl().setStyle("opacity", "0");
				},
				drop: {
					fn: function(i_dropbox, a_files, o_event) {
						var plugin = i_dropbox.getDDPlugin();
						var bodyEl = i_self.bodyEl;
						if (plugin.enableDrop) {
							var msg = ip2.i18n({
								da: "Kontrolerer file....",
								en: "Checking file..."
							});

							bodyEl.mask(msg);
							Ext.ux.file.util.Handler.checkFiles(i_dropbox.path, a_files, function(o_result) {
								bodyEl.unmask();
								var a_update = o_result.update;
								var a_create = o_result.create;
								var b_update = false;
								var b_cancel = false;
								var b_create = false;
								var a_result = [];
								if (a_update.length > 0) {
									b_update = true;
									Ext.ux.file.util.Handler.getUIConflickWindow(bodyEl, i_self, i_dropbox.path, a_update,
										function(cancel, a_records) {
											b_cancel = cancel;
											ip2.each(a_records, function(o_record) {
												a_result.push(o_record);
											});
											if (!b_create) {
												bodyEl.unmask();
												if (a_result.length > 0) {
													i_self.setValue(a_result);
												}
											}
											else {
												var msg = ip2.i18n({
													da: "Opretter file....",
													en: "Creating file..."
												});
												bodyEl.mask(msg);
											}
										}
									);
								}
								if (a_create.length > 0) {
									b_create = true;
									if (!b_update) {
										bodyEl.unmask();
										var msg = ip2.i18n({
											da: "Opretter file....",
											en: "Creating file..."
										});
										bodyEl.mask(msg);
									}
									Ext.ux.file.util.Handler.createRecords(i_dropbox.path, a_create, false, function(a_records) {
										b_create = false;
										ip2.each(a_records, function(o_record) {
											a_result.push(o_record);
										});
										if (!b_update) {
											bodyEl.unmask();
											i_self.setValue(a_result);
										}
										if (b_cancel) {
											bodyEl.unmask();
											i_self.setValue(a_result);
										}
									});
								}
							});
						}
					}
				},
				dragenter: {
					fn: function(i_dropbox, o_event) {
						var plugin = i_dropbox.getDDPlugin();
						var items = o_event.dataTransfer.items || o_event.dataTransfer.files;
						if (i_dropbox.maxItems) {
							if (items.length > i_dropbox.maxItems && i_dropbox.maxItems != -1) {
								i_dropbox.addCls(plugin.failureCls);
								plugin.enableDrop = false;
							}
						}
					}
				},
				dragleave: {
					fn: function(i_dropbox, o_event) {
						var plugin = i_dropbox.getDDPlugin();
						plugin.enableDrop = true;
					}
				}
			}
		});
		var i_dropzone = Ext.widget("container", {
			layout: "fit",
			renderTo: Ext.getBody(),
			style: {
				"background-color": "white",
				"position": "absolute",
				"top": "0px",
				"left": "0px",
				"right": "0px",
				"bottom": "0px",
				"display": "none",
				"opacity": "0"
			},
			items: [o_dropbox]
		});
		i_self.dropzone = i_dropzone;
		i_dropzone.getEl().insertBefore(el);
	},

	setValue: function(value, f_callback) {

		var i_self = this;
		var s_url = "";

		if (value && (typeof value !== "object")) {
			var s_path = ip2.cleanPath(i_self.path) + "/";
			var id = Number(value);
			if (Ext.isNumber(id)) {
				if (i_self.loadCount == 0) {
					i_self.loadCount++;
					Ext.ux.file.util.Handler.getRecordById(id, function(o_record) {
						if (o_record) {
							i_self.setValue(o_record, f_callback);
						}
					});
				}
			}
			else {
				if (i_self.loadCount == 0) {
					i_self.loadCount++;
					var a_split = value.split("/");
					var s_name = a_split.pop();
					var s_valuePath = a_split.join("/");
					if (s_valuePath) {
						s_path = s_valuePath + "/";
					}
					Ext.ux.file.util.Handler.getRecordByName(s_path, s_name, function(a_records) {
						if (a_records) {
							var o_record = a_records[0];
							i_self.setValue(o_record, f_callback);
						}
					});
				}
			}
		}
		else {
			i_self.loadCount = 0;
			if (value) {
				var o_record = undefined;

				if (Ext.isArray(value)) {
					o_record = value[0];
				}
				else {
					o_record = value;
				}
				if (o_record) {
					i_self.record = o_record;

					var b_isExternal = o_record.get("FILEXTERNAL");

					if (b_isExternal) {
						s_url = o_record.get("FILORIPATH");
					}
					else {
						s_url = o_record.get("FILPATH") + o_record.get("FILNAME");
					}
					i_self.setIconCls(i_self.getCSS(s_url));
					i_self.callParent(arguments);
					i_self.fireEvent("select", i_self, [o_record]);
					if (f_callback) {
						f_callback();
					}
				}
			}
		}
	},

	getRecord: function() {
		var i_self = this;
		return i_self.record;
	},

	isURL: function(value) {
		var s_value = String(value);
		var r_http = new RegExp('\\b(ftps?|https?)(:\/\/)', 'g');
		var a_match = s_value.match(r_http);
		return a_match ? true : false;
	},

	onHandelChange: function(item, value) {

		if (!value) {
			return;
		}
		var i_self = this;
		var i_el = i_self.bodyEl;
		var s_path = ip2.cleanPath(i_self.path) + "/";
		var i_fileField = i_self.getFileuploadField();
		var a_files = item.fileInputEl.dom.files;
		var s_extension = a_files[0].name.split(".").pop().toLowerCase();
		var a_extensions = i_self.extensions.split(",");

		if (a_extensions.indexOf(s_extension) != -1) {
			var el = i_self.triggerEl.elements[1];
			var msg = ip2.i18n({
				da: "Kontrolerer fil....",
				en: "Checking file..."
			});
			i_el.mask(msg);
			Ext.ux.file.util.Handler.checkFiles(s_path, a_files, function(o_result) {
				i_el.unmask();

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

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

				var a_result = [];

				if (a_update.length > 0) {
					b_update = true;
					Ext.ux.file.util.Handler.getUIConflickWindow(el, i_self, s_path, a_update, function(cancel, a_records) {
						b_cancel = cancel;
						ip2.each(a_records, function(o_record) {
							a_result.push(o_record);
						});
						if (!b_create) {
							i_el.unmask();
							i_self.setValue(a_result);
						}
						else {
							var msg = ip2.i18n({
								da: "Opretter filer....",
								en: "Creating files..."
							});
							i_el.mask(msg);
						}
					});
				}
				if (a_create.length > 0) {
					b_create = true;
					if (!b_update) {
						var msg = ip2.i18n({
							da: "Opretter filer....",
							en: "Creating files..."
						});
						i_el.mask(msg);
					}
					Ext.ux.file.util.Handler.createRecords(s_path, a_create, false, function(a_records) {
						b_create = false;
						ip2.each(a_records, function(o_record) {
							a_result.push(o_record);
						});
						if (!b_update) {
							i_el.unmask();
							i_self.setValue(a_result);
						}
						if (b_cancel) {
							i_el.unmask();
							i_self.setValue(a_result);
						}
					});
				}
			});
		}
		else {
			var s_title = ip2.i18n({
				da: "Fejl",
				en: "Error"
			});
			var s_msg = ip2.i18n({
				da: "Denne fil type er ikke tilladt",
				en: "This fil type is not allowed"
			});

			Ext.Msg.show({
				title: s_title,
				msg: s_msg,
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
		}
		item.reset();
	}
});
