'use strict';

(function () {

  // import Objects
  var ContactRepository = exports.contactRepository,
  ConverterFactory = exports.converterFactory,
  ContactStorage = exports.contactStorage,
  ContactReverser = exports.contactReverser,
  Message = exports.message,

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

  exports.contactConverter = {

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

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

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

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

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