/**
 * Card data is stored on localStorage, but also a copy is kept on memory. 
 * This class handles the update of the localStorage.
 *
 * TODO probably the Angular JS way to do this is using a service
 */
var CardStore = function() {
     //load cards from localStorage 
  var _cardsStr = localStorage.getItem('cards');
  var _cards = [];
  if (_cardsStr == null) {
    console.log("localStorage cards was empty");
  } else {
    _cards = JSON.parse(_cardsStr);
  }
  return {
    all: function() {
      return _cards;
    },
    create: function(cardData) {
      this.update(cardData);
    },
    //create or update
    update: function(cardData) {
      //set that the card was updated now
      if (cardData.card_number == undefined) {
        return;
      }
      cardData.updated_at = Date.now();
      found = false;
      //search for this card 
      // this is not an elegant way, but simple though...
      for(var i=0; i<_cards.length; i++) { 
        if (_cards[i].card_number == cardData.card_number) { 
          _cards[i] = cardData;
          found = true;
          break;
        }
      }
      if (found == false) { //add it to the array
        _cards.push(cardData);
      }
      //update localStorage
      //finally
      localStorage.setItem('cards',JSON.stringify(_cards));
    },
    delete: function(cardNumber) {
      for(var i=0; i<_cards.length; i++) {
        if (_cards[i].card_number == cardNumber) { 
          _cards.splice( i, 1 );
          break;
        }  
      } // for
      //update storage too
      localStorage.setItem('cards',JSON.stringify(_cards));
    }
  }
  
}

