import { Component, EventEmitter, Input, OnInit, Output, SimpleChanges } from '@angular/core';
import { IUser } from '../../models/user';
import { AppConfig } from '../../shared/app.config';

@Component({
  selector: 'fm-avatar',
  templateUrl: './avatar.component.html',
  styleUrls: ['./avatar.component.css']
})
export class AvatarComponent implements OnInit {

  @Input() user: IUser;
  @Input() bgColor: string;
  @Input() fgColor: string;
  @Input() size = 75;
  @Input() round = true;

  @Output() click = new EventEmitter();
  
  src : string = null;
  name : string = null;

  constructor(private appConfig: AppConfig) {
  }

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['user']) {
      const user: IUser = changes['user'].currentValue;
      this.refresh(user);
    }
  }

  onClick(event: MouseEvent) {
    event.stopPropagation();
    this.click.emit();
  }

  refresh(user: IUser) {
    if (!user) return null;
    const apiEndpoint = this.appConfig.getConfig("apiEndPoint");
    this.src = `${apiEndpoint}/api/v1/users/${user.code}/avatar`;
    this.name = user.firstName && user.lastName ? 
      user.firstName + ' ' + user.lastName : user.name;
  }
}