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

define(['backbone', 'underscore',
	'patient-search/models/Patient'
],
	function ( Backbone, _, Patient) {
		return Backbone.Collection.extend({
			url: function() {
				return this.restUrl;//Portal.resources().get('patients').get('href');
			},
			initialize: function(options) {
				this.restUrl = options.url;
			},
			model: Patient,
			parse: function(response, options) {
				if ( response["object-type"] !== "RecentlySelectedPatients" ) {

					if (response.paging) {

						var pageSize = response.paging.pageSize,
							thisPage = response.paging.thisPage;

						this.latestPage = thisPage;
						this.results = (thisPage - 1 ) * pageSize + response.size;
						this.totalResults = response.paging.totalResults;

					} else {

						this.latestPage = null;
						this.results = 0;
						this.totalResults = 0;
					}

					// TODO: sorting should come from backend once paging is back in place
					return _.sortBy(response.patient, "displayName");
				} else {
					this.latestPage = null;

					if (response.size > 0) {
						this.results = response.selectedPatient.length;
						this.totalResults = this.results;

						return response.selectedPatient;
					}
				}
			}
		});
	});