define([
	'Global',
	'MessagingView',
	'AppointmentRequest',
    'User',
    'MessagePopupView',
    'VAACPopupView',
	'Text!../html/templates/VAAC-collapsible.html'
],
	function (Global, MessagingView, AppointmentRequest, user, MessagePopupView, VAACPopupView, template) {
		'use strict';
		return Backbone.View.extend({
			id: "VAAC-request-details",
			attributes: {
				"data-collapsed": "false",
				"data-collapsed-icon": "arrow-r",
				"data-expanded-icon": "arrow-d",
				"data-role": "collapsible",
				"data-theme": "b"
			},
			initialize: function () {
				var that = this;

				this.template = _.template(template);

				this.listenTo(Global.getUtilities().eventAggregator, "clearVAACCollapsible", function() {
					that.remove();
				});
			},

			render: function () {
                var $container = getSidebarContent().find('#below-filter'),
                    appointmentRequest = AppointmentRequest.instance(),
                    requestId = appointmentRequest.get('uniqueId');

                this.$el
                    .empty()
                    .append(this.template(appointmentRequest.toJSON()))
                    .find('#VAAC-request-content')
                    .append(new MessagingView({id: requestId}).render().el);

                $container
                    .empty()
                    .append(this.$el)
                    .trigger('create');

				return this;
			},

			events: {
                "click #unavailable-btn": "showUnavailable",
                "click #cancel-VAAC-btn": "showCancel"
			},

            showCancel: function(){
                var that = this;
                new VAACPopupView({
                    callBacks: [
	                    function () {},
	                    that.handleCancel
                    ],
	                legend: "Cancelled By:",
	                checkboxRadios: this.getCancelCodeInfo(),
	                checkboxRadioType: "radio",
	                title: "Cancel Veteran Request"
                }).render();
            },

            showUnavailable: function(){
                var that = this,
	                secondRequest = AppointmentRequest.instance().get('secondRequest'),
	                alertMessage = secondRequest ? "This is the second failed request." : "",
	                alertMessageLine2 = secondRequest ? "PLEASE CALL THE VETERAN before updating the status.": "",
	                label = secondRequest ? "Not booked, unable to contact Veteran" : "Unable to meet request, First Attempt";

                new VAACPopupView({
	                alertMessage: alertMessage,
	                alertMessageLine2: alertMessageLine2,
                    callBacks: [
	                    function(){},
	                    that.handleUnavailable
                    ],
	                checkboxRadios: [
		                {
			                id: "mark-unavailable",
			                label: label,
			                value: "mark-unavailable"
		                }
	                ],
	                checkboxRadioType: "checkbox",
	                legend: "Update Status To:",
	                title: "Unavailable Appointment"
                }).render();
            },

            handleCancel: function(){
                var VAACRequestItem = AppointmentRequest.instance(),
                    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 () {
                            AppointmentRequest.clearInstance();
                            new MessagePopupView({
                                code: "200",
                                alertMessage: "Veteran Request successfully cancelled",
                                title: "Cancel Veteran Request"
                            }).render();
	                        Global.getUtilities().eventAggregator.trigger('clearVAACCollapsible');
                        },
                        500 : function () {
                            new MessagePopupView({
                                code: "500",
                                alertMessage: "ERROR: An error occurred while saving the veteran request",
                                title: "Cancel Veteran Request"
                            }).render();
                        }
                    }
                });
            },

            handleUnavailable: function(){
                var VAACRequestItem = AppointmentRequest.instance(),
                    ardc = VAACRequestItem.get('appointmentRequestDetailCode'),
                    detailCode = VAACRequestItem.get('secondRequest') ? "DETCODE4" : "DETCODE3",
                    url = VAACRequestItem.get('self').href;

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

                VAACRequestItem.save({
                    id: VAACRequestItem.get("uniqueId"),
                    status: "Not Booked"
                }, {
                    url: url,
                    statusCode: {
                        200 : function () {
                            AppointmentRequest.clearInstance();
                            new MessagePopupView({
                                code: "200",
                                alertMessage: "Appointment request successfully marked as Unavailable",
                                title: "Unavailable Appointment"
                            }).render();
	                        Global.getUtilities().eventAggregator.trigger('clearVAACCollapsible');
                        },
                        500 : function () {
                            new MessagePopupView({
                                code: "500",
                                alertMessage: "ERROR: An error occurred while saving the request",
                                title: "Unavailable Appointment"
                            }).render();
                        }
                    }
                });
            },

			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
			}
		});
	}
);
