import { AfterViewInit, Component, ElementRef, Input, OnInit, Renderer2, ViewChild } from '@angular/core';
import { IClientModel } from '@fleio-api/client-user/model/client.model';

@Component({
  selector: 'app-client-avatar',
  templateUrl: './client-avatar.component.html',
  styleUrls: ['./client-avatar.component.scss']
})
export class ClientAvatarComponent implements OnInit, AfterViewInit {
  @ViewChild('clientAvatar') clientAvatar: ElementRef;
  @Input() client: IClientModel;
  @Input() bigSquare = false;
  @Input() cssClass: string;
  shownText: string;
  backgroundColor: string;

  constructor(
    private renderer: Renderer2
  ) { }

  hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null;
  }

  ngOnInit(): void {
    if (this.client.company) {
      this.shownText = this.client.company[0].toLocaleUpperCase();
    } else{
      this.shownText = this.client.first_name[0].toLocaleUpperCase() + this.client.last_name[0].toLocaleUpperCase();
    }
  }

  ngAfterViewInit() {
    let hexNr;
    if (this.client?.id) {
      hexNr = this.client.id.toString();
    }
    if (!hexNr || !hexNr.length) {
      console.error('Client avatar cannot be built without client ID!');
    } else {
      while (hexNr.length < 6) {
        hexNr += hexNr;
      }
      if (hexNr.length > 6) {
        hexNr = hexNr.substring(0, 6);
      }
      const rgb = this.hexToRgb(`#${hexNr}`);
      this.renderer.setStyle(
        this.clientAvatar.nativeElement, 'background-color', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, .4)`
      );
      if (this.client.company) {
        if (Number.parseInt(this.client.id.toString(), 10) % 2 === 0) {
          this.renderer.setStyle(
            this.clientAvatar.nativeElement, 'background-position', 'center'
          );
        } else {
          this.renderer.setStyle(
            this.clientAvatar.nativeElement, 'background-position', 'top'
          );
        }
      } else {
        if (Number.parseInt(this.client.id.toString(), 10) % 2 === 0) {
          this.renderer.setStyle(
            this.clientAvatar.nativeElement, 'background-repeat', 'space'
          );
        } else {
          this.renderer.setStyle(
            this.clientAvatar.nativeElement, 'background-repeat', 'round'
          );
        }
      }
    }
  }

}
