'use strict';

(function () {

  // import Objects
  var Repository = exports.repository;

  // code
  exports.contactRepository = {

    getAll: function () {
      var data = navigator.mozContacts.getAll({});
      return Repository.getPromise(new ContactsBuilder(data));
    },

    save: function (contact) {
      var contacts = navigator.mozContacts.save(contact);
      return Repository.getPromise(contacts);
    }
  };

  function ContactsBuilder(data) {
    var obj = this;
    obj.current = 0;
    obj.contacts = [];
    data.onsuccess = function () {
      if (data.result) {
        obj.contacts.push(data.result);
        data.continue();
      } else {
        obj.onsuccess();
      }
    };
    data.onerror = function () {
      obj.onerror();
    };
  }

  ContactsBuilder.prototype = {

    onsuccess: function () {},

    onerror: function () {},

    next: function () {
      this.current++;
    }
  };
}());
