define([
    'Global',
    'BookedAppointment',
    'PatientContext'
],
    function(Global, BookedAppointment, PatientContext) {
        var that,
			BookedAppointments = Backbone.Collection.extend({
            model: BookedAppointment,
			url: function () {
				var patient = PatientContext.instance().getPatient();

				return patient.isValid() ? patient.get("patient-booked-appointments").href + "?startDate=" + formatDate(new Date()) : "";
			},
			initialize: function () {
				that = this;
			},
            parse: function(response) {
				var objectType = response["object-type"];

				objectType = objectType.substr(0, objectType.length - 1);
				objectType = objectType.charAt(0).toLowerCase() + objectType.slice(1);

                return response[objectType];
            },
			findById: function (id) {
				return this.find(function (model) {
					return model.get('appointmentId') === id;
				});
			},

			noCancelledAppts: function() {
				var that = this,
					appts = this.filter(function (model) {
						return !that.isCancelled(model.get('currentStatus'));
					});

				return new Backbone.Collection(appts);
			},

			isCancelled: function(status) {
				var cancelled = false;

				switch (status) {
					case "NO-SHOW":
					case "CANCELLED BY CLINIC":
					case "NO-SHOW & AUTO RE-BOOK":
					case "CANCELLED BY CLINIC & AUTO RE-BOOK":
					case "INPATIENT APPOINTMENT":
					case "CANCELLED BY PATIENT":
					case "CANCELLED BY PATIENT & AUTO-REBOOK":
					case "NO ACTION TAKEN":
						cancelled = true;
				}

				return cancelled;
			}
        });

        BookedAppointments.singleInstance = null;

        BookedAppointments.instance = function () {
            if (!BookedAppointments.singleInstance) {
		        BookedAppointments.singleInstance = new BookedAppointments();

		        if (BookedAppointments.singleInstance.url()) {
			        BookedAppointments.singleInstance.fetch({cache: false});
		        }
	        }

            return BookedAppointments.singleInstance;
        };

        return BookedAppointments;
    }
);
