/*jslint node: true, nomen: true, unparam: true */
/*global jquery, $, _, define, Marionette, Handlebars, jqm, describe, it, expect, beforeEach, spyOn */

define([ 'Global' , 'jquery.mobile-autocomplete', 'moment',
	'patient-search/models/Model',
	'patient-search/views/AutocompleteListView',
	'patient-search/views/PatientView'],
	function( Global, jqmAutocomplete, moment, model, AutocompleteListView, PatientView) {
		'use strict';
		var self;
		return AutocompleteListView.extend({
			itemView: PatientView,
			events: {
				'input .ui-accessible-autocomplete-filter input': 'setPatientFilterText',
				'change .ui-accessible-autocomplete-filter input': 'setPatientFilter',
				'tap .ui-accessible-autocomplete-filter a.ui-input-clear': 'clearPatientFilter',
				'tap ul a': 'preventDefault',
				'keyup ul a': 'keyupList'
			},
			collectionEvents: {
				'sync': 'refreshAutocomplete',
				'reset': 'refreshAutocomplete'
			},
			initialize: function (options) {
				self = this;
                this.options = options || {};
				this.vent = this.options.vent || new Backbone.Wreqr.EventAggregator();

                this.placeholder = options.placeholder || "Search Patient By Name or SSN...";
                this.noItemsMessage = "No Results Found";
                this.minLength = options.minLength || 2;
                this.onSubmit = options.onSubmit || true;
			},
			onRender: function () {
				var type = this.model.get('type'),
					autocompleteCallback = this._autocomplete();

				this.ui.autocompleteList.accessibleautocomplete({
					'populateList': autocompleteCallback.populateList,
					'selectItem': autocompleteCallback.selectItem,
					'filterItem': autocompleteCallback.filterItem,
					'filterPlaceholder': self.placeholder,
					'filterNoItemsMessage': self.noItemsMessage,
					'filterSubmit': this.onSubmit,
					'filterMinLength': self.minLength,
					'filterReveal': false,
					'inset': true,
					'splitIcon': 'star'
				});
				this.$el.trigger('create');
				this.$el.find('.ui-accessible-autocomplete-filter input').val(this.model.get('patientFilter'));
				this.doBasedOnType();
			},
			onClose: function () {
				$('#portal-modal .ui-content').off('scrollstop');
				this.stopListening();
				this.off();
			},
			setPatientFilterText: function (e) {
				var patientFilter = $(e.currentTarget).val();

				if (this.model.get('patientFilter') !== patientFilter) {
					this.model.set('patientFilter', patientFilter);
					if (patientFilter === "") {
						this.doBasedOnType();
					}
				}
			},
			setPatientFilter: function (e) {
				var activeLiAnchor = this.ui.autocompleteList.find('li.ui-btn-down-d a'),
					patientFilter = this.model.get('patientFilter').toUpperCase(),
					liIndex;

				if (activeLiAnchor.length === 0) {
					if (this.ui.autocompleteList.find('li:not(.ui-screen-hidden, .ui-li-static)').length > 0) {
						// switch to _.findIndex after updating to lodash 2.4.1
						_.find(this.collection.models, function (patient, index) {
							if (patient.get('displayName').toUpperCase() === patientFilter) {
								liIndex = index + 1;
								return true;
							}
						});
					}
				} else {
					activeLiAnchor.tap();
				}
			},
			clearPatientFilter: function (e) {
				e.preventDefault();
				$("#primary-search-filter .ui-input-text").val("");
				this.model.set('patientFilter', "");
				this.doBasedOnType();
			},
			fetchPage: function (e) {
				var nextPage = this.collection.latestPage + 1,
					size = this.collection.results,
					totalResults = this.collection.totalResults,
					atEndOfPage = e.currentTarget.scrollHeight - e.currentTarget.scrollTop <= e.currentTarget.clientHeight + 100;

				if (atEndOfPage && size < totalResults) {
					//var data = _.extend({page: nextPage}, this._autocomplete().fetchData());
					var data = this._autocomplete().fetchData() + "page=" + nextPage;

					this.collection.fetch({
						url: self.collection.url() + data,
						remove: false,
						dataType: "json"
						//data: data
					})
						.done(function (response) {
							// patients appended by Marionette
							//if (self._isRendered) { self.renderHeader(); }
						});
				} else if (size === totalResults) {
					$('#portal-modal .ui-content').off('scrollstop');
					this.hasPaging = false;
				}
			},
			doBasedOnType: function () {
				switch (this.model.get('id')) {
					case 'wards':
					case 'clinics':
						this._autocomplete().bootstrapPrepopulate();
						return;
					default:
						this.collection.reset();
				}
			},
			_autocomplete: function () {

				var self = this,
					hasPaging = false,
					headerCount = 0,

					fetchData = function () {
						var data = {},
							searchValue = self.$el.find('.ui-listview-filter input').val() || "",
							searchType = self.model.get('id'),
							location,
							startDate;

						if (searchValue.trim() !== "") {
							data.searchstring = encodeURIComponent(searchValue.trim());
						}

						if (self.model.has('location')) {
							location = self.model.get('location');

							if (searchType === 'clinics') {
								data.clinic = location.get('id');

								startDate = self.model.get('dateFilter');
								if (startDate !== "") {
									data.visitDate = moment(startDate).format('YYYYMMDD');
								}
							} else if (searchType === 'wards') {
								data.ward = location.get('id');
							}
						}
						// return data;
						var dataString = "?";
						_.forEach(_.keys(data), function (key) {
							dataString += key + "=" + data[key] + "&";
						});
						return dataString;
					},

					bootstrapPrepopulate = function () {
						var data = fetchData();
						self.ui.autocompleteList.accessibleautocomplete('option', 'filterNoItemsMessage', self.noItemsMessage);

						self.collection.fetch({
							url: self.collection.url() + data,
							dataType: "json"
							//data: data
						})
							.done(function (response) {
								//if (self._isRendered) { self.renderHeader(); }

								if (!hasPaging) {
									$('#portal-modal .ui-content').on('scrollstop', function (e) {
										self.fetchPage(e);
									});
									hasPaging = true;
								}
							})
							.fail(function (jqXHR) {
								self.collection.reset();

								if (jqXHR.status === 400) {
									list.accessibleautocomplete('option', 'filterNoItemsMessage', $.parseJSON(jqXHR.responseText).message);
									hasPaging = false;
								}
							});

					},

					populatePatientSearch = function (deferred, searchValue, list) {
						var data = fetchData();
						list.accessibleautocomplete('option', 'filterNoItemsMessage', self.noItemsMessage);

						self.collection.fetch({
							url: self.collection.url() + data,
							dataType: "json"
							//crossDomain: true,
							//data: data
						})
							.done(function (response) {
								//self.renderHeader();

								// patients appended by Marionette
								if (!hasPaging) {
									$('#portal-modal .ui-content').on('scrollstop', function (e) {
										self.fetchPage(e);
									});
									hasPaging = true;
								}
								// selects first link in list
								self.$el.find('ul a').eq(0).focus();
								return deferred.resolve();
							})
							.fail(function (jqXHR) {
								self.collection.reset();

								if (jqXHR.status === 400) {
									list.accessibleautocomplete('option', 'filterNoItemsMessage', $.parseJSON(jqXHR.responseText).message);
									hasPaging = false;
								}

								return deferred.resolve();
							});

						return deferred.promise();
					},

					showConfirmation = function (search, item) {
						var patient = self.collection.at(item.index() - headerCount);

						model.get('patient').set(patient.attributes);
						self.vent.trigger("open:popup:confirmation", {positionTo: item});
					},

					filterItem = function (text, searchValue, item) {
						return false; // leave filtering to server
					};

				return {
					fetchData: fetchData,
					bootstrapPrepopulate: bootstrapPrepopulate,
					populateList: populatePatientSearch,
					selectItem: showConfirmation,
					filterItem: filterItem
				};
			}
		});
	});
