using System;
using System.Data;
using System.Collections.Generic;
using System.Web;

using FourLayer.BusinessEntity;
using FourLayer.DataAccessObject;

namespace FourLayer.ApplicationLogic
{
   public enum CustomerServiceCardErrors
   {
      NoError, CardCancelled, CardExpired, CardNotFound, InsufficientCredit, NameMismatch,
   }
   /// <summary>
   /// Handles all the application logic for catalog
   /// </summary>
   public class CustomerServiceLogic
   {
      /*
      * CustomerCard
      */
      public EntityCollection<CustomerCard> GetAllCards()
      {
         CustomerCardDAO dao = new CustomerCardDAO();
         return dao.GetAll();
      }
      public CustomerCard GetCardByNumber(string cardNumber)
      {
         if (cardNumber == null)
            return null;

         CustomerCardDAO dao = new CustomerCardDAO();
         return dao.GetByKey(cardNumber);
      }
      public CustomerServiceCardErrors Purchase(string cardNumber, string cardName, decimal amount)
      {
         // first try to get this card
         CustomerCard card = GetCardByNumber(cardNumber);
         if (card == null)
            return CustomerServiceCardErrors.CardNotFound;

         // ensure card number and name match
         if (cardName != card.CardName)
            return CustomerServiceCardErrors.NameMismatch;

         // see if card cancelled
         if (card.IsCancelled)
            return CustomerServiceCardErrors.CardCancelled;

         // see if card expired
         if (card.IsExpired)
            return CustomerServiceCardErrors.CardExpired;

         // see if enough credit
         if (card.IsOverCreditLimit)
            return CustomerServiceCardErrors.InsufficientCredit;

         // everything okay so try to do purchase
         CustomerCardErrors purchaseError = card.Purchase(amount);
         if (purchaseError == CustomerCardErrors.OverCreditLimit)
            return CustomerServiceCardErrors.InsufficientCredit;
         else
         {
            // now save the purchase
            CustomerCardDAO dao = new CustomerCardDAO();
            dao.UpdateBalanceHold(card);
            return CustomerServiceCardErrors.NoError;
         }
      }
   }
}