'use strict';

(function () {

  // import Objects
  var ContactRepository = exports.contactRepository,
  ContactStorage = exports.contactStorage,
  Message = exports.message,

  // code
  updateEvent = new BusinessEvent('revert.update'),
  startEvent = new BusinessEvent('revert.start'),
  endEvent = new BusinessEvent('revert.end'),
  notification = document.getElementById('notification');

  exports.contactReverser = {

    revert: function (data) {
      startEvent.trigger(data.contacts.length);
      revert(data);
    }
  };

  function revert(data) {
    var contact = data.contacts[data.current];
    if (contact) {
      updatePhone(contact);
      saveContact(contact, data);
    } else {
      ContactStorage.clear();
      endEvent.trigger();
    }
  }

  function updatePhone(contact) {
    var i, phone, phones;
    phones = contact.tel;
    for (i = 0; i < phones.length; i++) {
      phone = phones[i];
      setPhone(phone, ContactStorage.getPhone(''+contact.id+phone.value));
    }
  }

  function setPhone(phone, number) {
    if (number) {
      phone.value = number;
    }
  }

  function saveContact(contact, contactsData) {
    var promise = ContactRepository.save(contact);
    promise.then(function (data) {
      updateEvent.trigger(contactsData.current);
      contactsData.next();
      revert(contactsData);
    });
    promise.otherwise(function (data) {
      Notifier.notify(notification, Message['title.unexpected'], data.error);
    });
  }
}());
