define([
    'Global',
    'HeaderView',
	'SelectedDetails',
    'PatientContext',
	'WaitListEntry',
	'AppointmentRequest',
	'DesiredDate',
	'Patient',
	'PatientSimpleDetailsView',
    'Text!../html/templates/EWL-details.html',
	'Text!../html/templates/NEAR-details.html',
	'Text!../html/templates/recall-details.html',
    'Text!../html/templates/request-status.html'
],
    function (Global, HeaderView, SelectedDetails,PatientContext, WaitListEntry, AppointmentRequest, DesiredDate, Patient, PatientSimpleDetailsView,
			  EWLDetailsTemplate, NEARDetailsTemplate, RecallDetailsTemplate, requestStatusTemplate) {
        'use strict';
        var thisView;

        var WaitListDetailsView = Backbone.View.extend({
	        className: "wait-list-details",
            initialize: function () {
                this.EWLTemplate = _.template(EWLDetailsTemplate);
				this.NEARTemplate = _.template(NEARDetailsTemplate);
				this.RecallTemplate = _.template(RecallDetailsTemplate);
                this.requestStatusTemplate = _.template(requestStatusTemplate);
				this.selectedDetails = SelectedDetails.instance();
                thisView = this;
                this.delegateEvents();
                this.inProcess = false;
				this.listenTo(this.selectedDetails, 'change', function () {
					var whatChanged = this.selectedDetails.get('whatChanged');

					switch (whatChanged) {
						case "id":
							thisView.id = thisView.selectedDetails.getId();

							thisView.render();
							break;
						case "collection":
							thisView.collection = thisView.selectedDetails.getCollection();
							break;
					}

					this.selectedDetails.set('whatChanged', '');
				});
            },
            render: function () {
				var that = this,
					id = this.id,
					details;

				this.details = this.collection.findById(id);

				details = this.details.toJSON();
				if(this.details.getServiceConnectedCode){
					$.extend(details, {serviceConnectedCode: this.details.getServiceConnectedCode() });
				}

                this.$el
                    .empty()
                    .append(thisView.requestStatusTemplate({inUse: false, lockedByUser: false}));

				this.changeTemplate(details.type);

				this.$el
					.append(this.template(details));

				getMainContent().empty();

				getMainContent()
					.append(this.$el)
					.trigger('create');

				$('#process-request').button('disable');

	            if (!this.patientWaitList) {
		            new Patient().fetch({
			            cache: false,
			            url: this.details.get("patientLink"),
			            success: function (data) {
				            if ($('.' + that.className).length) {
					            that.viewpatient = data;
					            PatientSimpleDetailsView.instance().render(data);
					            $('#process-request').button('enable').focus();
				            }
			            }
		            });
	            } else {
		            $('#process-request').button('enable').focus();
	            }

				this.delegateEvents();

				$(document).jqmData('requestHref-for-detail-viewing', '');

				this.details = details;

				return this;
            },
			changeTemplate: function (type) {
				var that = this;

				switch (type) {
					case "EWL":
						that.template = that.EWLTemplate;
						break;
					case "NEAR":
						that.template = that.NEARTemplate;
						break;
					case "RECALL":
						that.template = that.RecallTemplate;
						break;
				}
			},
            events: {
                'click #process-request:not(.ui-disabled)': "goToBooking"
            },
            goToBooking: function () {
	            $('#process-request').button('disable');
                this.inProcess = true;
            	this.changePatient();
            },
			changePatient: function () {
				var that = this;

				if (!this.patientWaitList) {
					PatientContext.instance().createContext({
						patient: this.viewpatient.toJSON(),
						success: function () {
							Global.getUtilities().eventAggregator.trigger('refreshPatientAppts');

							that.setWaitListDetails(that.details);

							that.goToBookingTab();
						}
					});
				} else {
					this.setWaitListDetails(this.details);

					this.goToBookingTab();
				}
	        },
	        setWaitListDetails: function (details) {
		        WaitListEntry.instance(details);

		        AppointmentRequest.clearInstance();

		        DesiredDate.clearInstance();
	        },
	        goToBookingTab: function () {
		        var hash = window.location.hash;

		        $(document).jqmData('patientView', false);

		        if (hash === "#booking") {
			        Backbone.history.stop();
			        Backbone.history.start();
		        } else {
			        Global.getUtilities().eventAggregator.trigger("booking");
		        }
	        }
        });

		WaitListDetailsView.singleInstance = null;

		WaitListDetailsView.instance = function (options) {
            this.options = options || {};

			WaitListDetailsView.singleInstance = WaitListDetailsView.singleInstance || new WaitListDetailsView();

			WaitListDetailsView.singleInstance.patientWaitList = this.options.patientWaitList;

			return WaitListDetailsView.singleInstance;
		};

		return WaitListDetailsView;
    }
);
