const { omit, compact, map } = require('lodash');

const { toLogFormat } = require('./errors');

exports.parseAndWriteContactAvatar = upgradeAttachment => async (
  contact,
  context = {}
) => {
  const { message } = context;
  const { avatar } = contact;
  const contactWithUpdatedAvatar =
    avatar && avatar.avatar
      ? Object.assign({}, contact, {
          avatar: Object.assign({}, avatar, {
            avatar: await upgradeAttachment(avatar.avatar, context),
          }),
        })
      : omit(contact, ['avatar']);

  // eliminates empty numbers, emails, and addresses; adds type if not provided
  const contactWithCleanedElements = parseContact(contactWithUpdatedAvatar);

  const error = exports._validateContact(contactWithCleanedElements, {
    messageId: idForLogging(message),
  });
  if (error) {
    console.log(
      'Contact.parseAndWriteContactAvatar: contact was malformed.',
      toLogFormat(error)
    );
  }

  return contactWithCleanedElements;
};

function parseContact(contact) {
  return Object.assign(
    {},
    omit(contact, ['avatar', 'number', 'email', 'address']),
    parseAvatar(contact.avatar),
    createArrayKey('number', compact(map(contact.number, cleanBasicItem))),
    createArrayKey('email', compact(map(contact.email, cleanBasicItem))),
    createArrayKey('address', compact(map(contact.address, cleanAddress)))
  );
}

function idForLogging(message) {
  return `${message.source}.${message.sourceDevice} ${message.sent_at}`;
}

exports._validateContact = (contact, options = {}) => {
  const { messageId } = options;
  const { name, number, email, address, organization } = contact;

  if ((!name || !name.displayName) && !organization) {
    return new Error(
      `Message ${messageId}: Contact had neither 'displayName' nor 'organization'`
    );
  }

  if (
    (!number || !number.length) &&
    (!email || !email.length) &&
    (!address || !address.length)
  ) {
    return new Error(
      `Message ${messageId}: Contact had no included numbers, email or addresses`
    );
  }

  return null;
};

function cleanBasicItem(item) {
  if (!item.value) {
    return null;
  }

  return Object.assign({}, item, {
    type: item.type || 1,
  });
}

function cleanAddress(address) {
  if (!address) {
    return null;
  }

  if (
    !address.street &&
    !address.pobox &&
    !address.neighborhood &&
    !address.city &&
    !address.region &&
    !address.postcode &&
    !address.country
  ) {
    return null;
  }

  return Object.assign({}, address, {
    type: address.type || 1,
  });
}

function parseAvatar(avatar) {
  if (!avatar) {
    return null;
  }

  return {
    avatar: Object.assign({}, avatar, {
      isProfile: avatar.isProfile || false,
    }),
  };
}

function createArrayKey(key, array) {
  if (!array || !array.length) {
    return null;
  }

  return {
    [key]: array,
  };
}

@@ -88,16 +88,322 @@
 rrors');
+%0Aconst %7B SignalService %7D = require('../../../ts/protobuf');%0A%0Aconst DEFAULT_PHONE_TYPE = SignalService.DataMessage.Contact.Phone.Type.HOME;%0Aconst DEFAULT_EMAIL_TYPE = SignalService.DataMessage.Contact.Email.Type.HOME;%0Aconst DEFAULT_ADDRESS_TYPE =%0A  SignalService.DataMessage.Contact.PostalAddress.Type.HOME;
 %0A%0Aexport
@@ -1500,29 +1500,29 @@
 umber, clean
-Basic
+Phone
 Item))),%0A   
@@ -1574,29 +1574,29 @@
 email, clean
-Basic
+Email
 Item))),%0A   
@@ -2380,13 +2380,13 @@
 lean
-Basic
+Phone
 Item
@@ -2487,33 +2487,212 @@
 e: item.type %7C%7C 
-1
+DEFAULT_PHONE_TYPE,%0A  %7D);%0A%7D%0A%0Afunction cleanEmailItem(item) %7B%0A  if (!item.value) %7B%0A    return null;%0A  %7D%0A%0A  return Object.assign(%7B%7D, item, %7B%0A    type: item.type %7C%7C DEFAULT_EMAIL_TYPE
 ,%0A  %7D);%0A%7D%0A%0Afunct
@@ -3026,9 +3026,28 @@
  %7C%7C 
-1
+DEFAULT_ADDRESS_TYPE
 ,%0A  

Use protobuf enum values to eliminate magic numbers