import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { Md5 } from 'ts-md5';

@Component({
  selector: 'app-gravatar',
  templateUrl: './gravatar.component.html',
  styleUrls: ['./gravatar.component.scss']
})
export class GravatarComponent implements OnInit, OnChanges {
  @Input() email: string;
  @Input() customStyle: Record<string, unknown>;
  @Input() cssClass: string;
  @Input() imgTitle = '';
  url: string;

  constructor() {
  }

  ngOnInit() {
    this.setUrl();
  }

  setUrl() {
    this.url = 'https://www.gravatar.com/avatar/';
    const md5 = new Md5();
    if (this.email) {
      this.url = this.url + md5.appendStr(this.email.trim().toLowerCase()).end() + '?default=identicon';
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes && changes.email && changes.email.previousValue) {
      // reset gravatar url if email changes value
      this.setUrl();
    }
  }

}
