Discount = function(data) {
  this.data = {};
  this.error = null;  

  if(data) {
      for (var key in data) {
          this.data[key] = data[key];
      }
	
	// compatibility with restaurant offers FIXME: create same format
	this.data.startTime = this.data.startTime || this.data.start_time;
	this.data.endTime = this.data.endTime || this.data.end_time;
	this.data.discountType = this.data.discountType || this.data.discount_type;
	this.data.minSpend = this.data.minSpend || this.data.minimum_spend;
	
  } else {
    this.error = "No such code!";
  }
}

Discount.prototype = {
  
 valid: function(total) {

   var now = new Date,
       start_time = new Date(this.data.startTime.year, (parseInt(this.data.startTime.month)-1), this.data.startTime.day, this.data.startTime.hour, this.data.startTime.minutes, 0, 0)
       end_time = new Date(this.data.endTime.year, (parseInt(this.data.endTime.month)-1), this.data.endTime.day, this.data.endTime.hour, this.data.endTime.minutes, 0, 0);
   
   if(now < start_time) {
     this.error = "Valid from " + start_time
   } else if(end_time < now) {
     this.error = "Expired " + end_time
   } else if(this.above_cap()) {
     this.error = "Too many uses"
   } else if(Number(total) < Number(this.data.minSpend)) {
     this.error = "Below the &pound;" + Number(this.data.minSpend).toFixed(2) + " minimum spend"
   } else if(Number(this.data.archived)) {
     this.error = "Expired"
   }
   
   return this.error == null
 },
 
 above_cap: function() {
   return (Number(this.data.cap) > 0 && Number(this.data.orders_count) >= Number(this.data.cap))
 },
 
 applicable: function(total) {
   return this.valid() && Number(total) < Number(this.data.minSpend);
 },
 
 amount: function(total) {

   if(Number(total) < Number(this.data.minSpend)) return 0;
 
   if(this.data.discountType == 0) {
     return (Math.round(Number(total) * Number(this.data.amount)) / 100)
   } else {
     return this.data.amount
   }
 }
  
}
