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

@Component({
  selector: 'neu-chip',
  templateUrl: './neu-chip.component.html',
  styleUrls: ['./neu-chip.component.css']
})
export class NeuChipComponent implements AfterViewInit {

  @Input() color:string;
  @ViewChild("neu_chip") neu_chip:ElementRef;

  constructor() { }

  ngAfterViewInit(): void {
    //color
    if(this.color!=null) {
      if(this.color=="primary") this.color = "#8B278F";
      else if(this.color=="secondary") this.color = "#2D3891";

      const hsl = this.toHsl(this.color);
      if(hsl.l <=80) {
        this.neu_chip.nativeElement.firstElementChild.style.color = "#F8F8FC";
        this.neu_chip.nativeElement.style.color = "#F8F8FC";
      }

      const elMesClar = 'hsl(' + hsl.h + ', ' + hsl.s + '%, ' + (hsl.l+10) + '%)';
      const elMesFosc = 'hsl(' + hsl.h + ', ' + hsl.s + '%, ' + (hsl.l-10) + '%)';
      const val = `linear-gradient(135deg, ${elMesFosc} -50%, ${elMesClar} 120%)`;
      this.neu_chip.nativeElement.style.backgroundImage = val;
    }
  }

  toHsl(hex:string) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

    var r = parseInt(result[1], 16);
    var g = parseInt(result[2], 16);
    var b = parseInt(result[3], 16);

    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b), min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min){
        h = s = 0; // achromatic
    } else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    s = s*100;
    s = Math.round(s);
    l = l*100;
    l = Math.round(l);
    h = Math.round(360*h);

    return { h:h, s:s, l:l };
  }

}
