export default class Name {
  constructor(
    salutation,
    nameFirst,
    nameMiddle,
    nameLast,
    initials,
  ) {
    this.salutation = this._sanitizeNamePart(salutation);
    this.nameFirst = this._sanitizeNamePart(nameFirst);
    this.nameMiddle = this._sanitizeNamePart(nameMiddle);
    this.nameLast = this._sanitizeNamePart(nameLast);
    this.initials = this._formatInitials(this._sanitizeNamePart(initials));
  }

  static fromContactPersonItem(item) {
    return new this(
      item.salutation,
      item.firstname,
      item.middlename,
      item.lastname,
      item.initials,
    );
  }

  _sanitizeNamePart(value) {
    if (this._isNamePartValid(value)) {
      return value.trim();
    } else {
      return '';
    }
  }

  _isNamePartValid(value) {
    return typeof value === 'string' && value.length;
  }

  _formatInitials(initials) {
    return initials.replace(/[^a-zA-Z]/g, '')
      .toUpperCase()
      .split('')
      .map(x => `${x}.`)
      .join('');
  }

  get nameFull() {
    const nameParts = [
      this.salutation,
      this.initials || this.nameFirst,
      this.nameMiddle,
      this.nameLast,
    ];

    return nameParts.filter(x => x).join(' ');
  }
};
