define([
	'Global',
	'User',
	'Resources'
],
	function(Global, user, resources) {
		'use strict';
		return Backbone.Model.extend({
			defaults: {
				"object-type": "Consult",
				"dataIdentifier": {
					"systemId": ""
				},
				"patientIdentifier": {
					"uniqueId": "",
					"assigningAuthority": ""
				},
				"alert": "",
				"consultId": "",
				"consultIen": "",
				"createdDate": "",
				"link": [
					{
						href: ""
					}
				],
				"patientDfn": "",
				"patientName": "",
				"requestDate": "",
				"sendingProviderDuz": "",
				"sendingProviderName": "",
				"serviceIen": "",
				"serviceName": "",
				"status": "",
				"text": "",
				"daysOnList": 0,
				"title": ""
			},

			config: {
				"rules":[
					{
						daysOnListLessThan: 5,
						title: "",
						icon: ""
					},
					{
						daysOnListLessThan: 7,
						title: "Nearing 7-day",
						icon: "alert-near"
					},
					{
						daysOnListLessThan: 8,
						title: "At 7-day",
						icon: "alert-on"
					},
					{
						daysOnListLessThan: 35,
						title: "Past 7-day",
						icon: "alert-past"
					},
					{
						daysOnListLessThan: 37,
						title: "Nearing 37-day",
						icon: "alert-near"
					},
					{
						daysOnListLessThan: 38,
						title: "At 37-day",
						icon: "alert-on"
					}
				],
				default: {
					title: "Past 37-day",
					icon: "alert-past"
				}
			},

			initialize: function () {
			},
			doubleDigit: function (digit) {
				return ('0' + digit).slice(-2);
			},

			getHtml: function(rule, daysOnList) {
				var icon = rule.icon || "",
					className = ' class="alert ' + icon + '"';
				return '<span data-sort="' + this.doubleDigit(daysOnList) + '"' + className + ' title="' + rule.title + '">' + daysOnList + "</span>";
			},

			getAlert: function (daysOnList) {
				var rules = this.config.rules,
					that = this;

				_.each(rules, function(rule) {
					if (daysOnList < rule.daysOnListLessThan) {
						return that.getHtml(rule, daysOnList);
					}
				});

				return this.getHtml(this.config.default, daysOnList);
			},
			parse: function (response) {
				var facilityCode = user.toJSON()['vistaLocation'],
					patientLink = resources.get('system-root').get('href') + "patient/dfn-" + facilityCode + "/" + response.patientDfn;

				response.patientLink = patientLink;
				response.consultIen = response.consultIen || response.consultId || 0;
				response.detailsLink = response.link[0] && response.link[0].href ? response.link[0].href : "";
				response.detailsId = response.consultIen;
				response.createdDate = response.createdDate ? response.createdDate.split(" ")[0] : "";
				response.requestDate = response.requestDate ? response.requestDate.split(" ")[0] : response.createdDate || "";
				response.serviceName = response.serviceName || response.text || "";
				response.daysOnList = this.getAlert(response.daysOnList);

				return response;
			}
		});
	}
);