define([
        'Global',
        'PatientContext',
        'Patient',
        'MessagingView',
        'AppointmentRequest',
		'DesiredDate',
        'VAACPopupView',
        'MessagePopupView',
        'HeaderView',
        'PatientSimpleDetailsView',
		'NotificationPrefs',
		'NotificationPrefView',
        'User',
        'Resources',
        'Text!../html/templates/appointment-request-details.html',
        'Text!../html/templates/request-status.html',
        'Text!../html/templates/request-patient-name.html'
    ],
    function (Global, PatientContext, Patient, MessagingView, AppointmentRequest, DesiredDate, VAACPopupView, MessagePopupView, HeaderView, PatientSimpleDetailsView, NotificationPrefs, NotificationPrefView, user, resources, appointmentRequestDetailsTemplate, requestStatusTemplate, requestPatientNameTemplate) {
        'use strict';
        var thisView;
        return Backbone.View.extend({
	        className: 'veteran-request-details',
            initialize: function (options) {
                this.options = options || {};
                thisView = this;
                this.afterCancelRequest = options && options.afterCancelRequest ? options.afterCancelRequest : function () {
                };
                this.template = _.template(appointmentRequestDetailsTemplate);
                this.patientTemplate = _.template(requestPatientNameTemplate);
                this.statusTemplate = _.template(requestStatusTemplate);
                this.appointmentRequestUrl = $(document).jqmData('requestId-for-detail-viewing');
            },

            render: function () {
                var that = this,
                    appointmentRequest = new AppointmentRequest();

                appointmentRequest.fetch({
	                cache: false,
                    url: that.appointmentRequestUrl,
                    success: function () {
                        that.appointmentRequest = appointmentRequest;

	                    Global.getUtilities().flattenLinks(that.appointmentRequest);

                        var $container = getMainContent(),
                            $view = that.$el,
                            template = that.template,
                            statusTemplate = that.statusTemplate,
                            patientTemplate = that.patientTemplate,
                            details = that.appointmentRequest.toJSON(),
                            title = that.getTitleAndUpdateProcessButton(),
	                        notificationPrefs = new NotificationPrefs({url: details["patient-notification-pref"].href});

                        that.disabled = false;
                        that.allowProcess = that.isProcessAllowedForAppointmentRequest();

                        if (that.allowProcess) {
                            var inUse = that.appointmentRequest.get("beingProcessedBy"),
                                lockedByUser = false;

                            if (inUse) {
                                if (inUse.userId === user.get('id')) {
                                    lockedByUser = true;
                                } else {
                                    that.disabled = true;
                                }
                            } else {
                                inUse = false;
                            }

                            statusTemplate = statusTemplate($.extend(details, {title: title, inUse: inUse, lockedByUser: lockedByUser}));

                            patientTemplate = patientTemplate(details) + statusTemplate + template(details);
                        } else {
                            patientTemplate = patientTemplate(details) + template(details);
                        }

                        $view.empty().append(patientTemplate);

                        Global.getUtilities().flattenLinks(that.appointmentRequest);

                        if (!that.appointmentRequest.get('providerSeenAppointmentRequest')) {
                            var aptRequest = that.appointmentRequest;
                            $.ajax({
                                type: "PUT",
                                url: aptRequest.get('appointment-request-provider-seen-flag').href,
                                data: "{}",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function () {
                                    aptRequest.attributes.providerSeenAppointmentRequest = true;
                                },
                                error: function (err) {
                                }
                            });
                        }

                        $view
                            .find('#messaging')
                            .append(new MessagingView({id: details.uniqueId}).render().el);

                        $container
                            .empty()
                            .append($view)
                            .trigger('create');

	                    new NotificationPrefView({model: notificationPrefs});

	                    notificationPrefs.fetchInfo();

                        var processRequest = $('#process-request');
                        if(processRequest.length){
                            processRequest[0].disabled = true;
                        }

                        $.ajax({
                            url: details["vista-patient-identifier"].href + "?parentSiteCode=" + user.get('vistaLocation'),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (response) {
                                var id = response && response.uniqueId ? response.uniqueId : "",
                                    assigningAuthority = response && response.assigningAuthority ? response.assigningAuthority : "",
                                    patientLink = id && assigningAuthority ? resources.get('system-root').get('href') + "patient/" + assigningAuthority + "/" + id : "";

                                if (patientLink) {
                                    new Patient().fetch({
	                                    cache: false,
                                        url:patientLink,
                                        success:function(data){
	                                        if ($('.' + that.className).length) {
		                                        that.viewpatient = data;
		                                        PatientSimpleDetailsView.instance().render(data);
		                                        that.enableProcessButton();
	                                        }
                                        },
	                                    error: function() {
		                                    new MessagePopupView({title: "Error", alertMessage: "Error retrieving patient information.  Please contact your system administrator for assistance."}).render();
	                                    }
                                    });
                                }
                                else{
                                    $("#patient-simple-details").detach();
                                }
                            },
                            type: "GET"
                        });

                        return that;
                    }
                });
            },
            events: {
                'click #process-request:not(.ui-disabled)': 'handleRequest'
            },

            getTitleAndUpdateProcessButton: function () {
                var title = "Process Request";
                this.requestFunction = this.processRequest;

                return title;
            },

            handleRequest: function () {
	            $('#process-request')[0].disabled = true;

                var url = this.appointmentRequest.get('self').href,
                    that = this;

                $.ajax({
                    url: url + '/inprocess',
                    success: function () {
                        that.changePatient(that.requestFunction, that);
                    },
                    type: "POST"
                });
            },

            processRequest: function (that) {
	            AppointmentRequest.clearInstance();
                AppointmentRequest.instance(that.appointmentRequest.toJSON());

                $(document).data("patientView", false);

                Global.getUtilities().eventAggregator.trigger('booking');
            },

            cancelRequest: function (that) {
                new VAACPopupView({
                    alertMessage: "You are canceling the appointment request only.",
                    alertMessageLine2: "Please cancel scheduled appointments through the Future Appointment list.",
                    callBacks: [
                        that.clearRequestLock,
                        that.handleCancel
                    ],
                    legend: "Cancelled By:",
                    checkboxRadios: that.getCancelCodeInfo(),
                    checkboxRadioType: "radio",
                    title: "Cancel Veteran Request"
                }).render();
            },

            clearRequestLock: function () {
                var url = thisView.appointmentRequest.get('self').href;

                $.ajax({
                    type: "DELETE",
                    url: url + "/inprocess"
                });
            },

            handleCancel: function () {
                var VAACRequestItem = thisView.appointmentRequest,
                    ardc = VAACRequestItem.get('appointmentRequestDetailCode'),
                    detailCode = $('#VAAC-form').serializeArray()[0].value,
                    url = VAACRequestItem.get('self').href;

                ardc.unshift({
                    userId: user.get('id'),
                    detailCode: {
                        code: detailCode
                    }
                });

                VAACRequestItem.save({
                    id: VAACRequestItem.get("uniqueId"),
                    status: "Cancelled"
                }, {
                    url: url,
                    statusCode: {
                        200: function () {
                            new MessagePopupView({
                                code: "200",
                                alertMessage: "Veteran Request successfully cancelled",
                                title: "Cancel Veteran Request"
                            }).render();
                            thisView.afterCancelRequest();
                            thisView.render();
                        },
                        500: function () {
                            AppointmentRequest.clearInstance();
                            new MessagePopupView({
                                code: "500",
                                alertMessage: "ERROR: An error occurred while saving the veteran request",
                                title: "Cancel Veteran Request"
                            }).render();
                        }
                    }
                });
            },

            isProcessAllowedForAppointmentRequest: function () {
                var status = this.appointmentRequest.get('status'),
                    detailCode = this.appointmentRequest.get('appointmentRequestDetailCode');

                detailCode = detailCode.length > 0 ? detailCode[0].detailCode : null;

                return (status === 'Submitted' || (status === 'Cancelled' && detailCode && detailCode.code === 'DETCODE8'));
            },

            enableProcessButton: function () {
                var $processRequest = $('#process-request');

                if (!this.disabled && $processRequest.length) {
                    $processRequest[0].disabled = false;
                    $processRequest.focus();
                } else {
                    $('#new-message').focus();
                }
            },

            changePatient: function (callBack, context) {
                PatientContext.instance().createContext({
                    patient: this.viewpatient.toJSON(),
                    success: function () {
	                    new HeaderView().render();

	                    Global.getUtilities().eventAggregator.trigger('refreshPatientAppts');

//	                    WaitListEntry.clearInstance();

	                    DesiredDate.clearInstance();

	                    if (callBack && $.isFunction(callBack)) {
		                    callBack(context);
	                    }
                    }
                });
            },

            getCancelCodeInfo: function () {
                var request = AppointmentRequest.instance(),
                    status = request.get('status'),
                    existingAppointmentRequestDetailCodes = request.get('appointmentRequestDetailCode'),
                    codeInfo = [];

                if (status === 'Cancelled' && existingAppointmentRequestDetailCodes !== null) {
                    var cancellationNotConfirmedByClerk = existingAppointmentRequestDetailCodes.every(
                        function (arDetCode) {
                            return (arDetCode.detailCode.code !== 'DETCODE7');
                        }
                    );

                    if (cancellationNotConfirmedByClerk) {
                        codeInfo.unshift({
                            id: "DETCODE7",
                            label: "Veteran - VA Confirmed",
                            value: "DETCODE7"
                        })
                    }
                } else {
                    codeInfo = [
                        {
                            id: "DETCODE6",
                            label: "Veteran",
                            value: "DETCODE6"
                        },
                        {
                            id: "DETCODE5",
                            label: "Clinic",
                            value: "DETCODE5"
                        }
                    ];
                }

                return codeInfo
            },
            templateHelpers: function(){
                return{
                    isBooked: function(){
                        return /^Booked$/i.test(this.status);
                    },
                    hasBookedApptDateTime: function(){
                        return this.bookedApptDateTime || false;
                    },
                    hasRequestedDate: function(){
                        return this.appointmentDate || false;
                    },
                    hasRequestDetailCode: function(){
                        return (this.appointmentRequestDetailCode || "").length > 0;
                    }
                }
            }
        });
    }
);
