import { Component, OnInit, Input } from '@angular/core';

import { BooleanFieldValue } from '../annotations/field-value';

@Component({
  selector: 'en-avatar',
  template: require('./en-avatar.component.html'),
  styles:   [require('./en-avatar.component.scss')]
})
export class EnAvatarComponent implements OnInit {

  /**
   * source of avatar image
   */
  @Input() src:string;

  /**
   * first name
   * required to create initials image
   */
  @Input() fName: string;

  /**
   * last name
   * required to create initials image
   */
  @Input() lName: string;

  /**
   * If separate fName and lName are not available.
   * Using this the initials placeholder will not be generated.
   */
  @Input() label: string;

  /**
   * if set, avatar is 120px wide. 60px by default.
   *
   */
  @Input() @BooleanFieldValue() avatar2x: boolean;

  /**
   * if present inverse the label color
   */
  @Input() @BooleanFieldValue() inverse: boolean;

  /**
   * used in template. if no src is set, it will be set to base64 svg image with initials
   * WIP
   */
  private _bgImage: string;

  constructor() {
  }

  ngOnInit() {
    if (!this.src && !(this.fName || this.lName)) {
      throw new Error('EnAvatar has to have either [src] or at least one of [fName] and [lName]');
    }

    if (!!this.src) {
      this._bgImage = `url('${this.src}')`;
    } else if (this.fName || this.lName) {
      let initials: string;
      if (this.fName) {
        if (this.lName) {
          initials = this.fName[0] + this.lName[0];
        } else {
          initials = this.fName[0] + this.fName[1];
        }
      } else {
        initials = this.lName[0] + this.lName[1];
      }

      initials     = `<svg xmlns="http://www.w3.org/2000/svg">
                        <text font-size="30" fill="black">${initials}</text>
                      </svg>`;
      this._bgImage = 'url(\'data:image/svg+xml;utf8,' + initials + '\')';
    } else {
      this._bgImage = 'none';
    }
  }
}
