import { Component, OnInit, Input,AfterViewInit } from '@angular/core';
import { IColorMap, IColor, IColorEntry,ILayer, IRenderer } from '../../models/color.map';


@Component({
    selector: 'fm-map-layer-legend',
    templateUrl: './legend.component.html',
    styleUrls: ['./legend.component.scss'],
    standalone: false
})
export class LegendComponent implements OnInit,AfterViewInit {

  constructor()  {

  }

  ngOnInit() {
  }

  ngAfterViewInit() {
  }

  @Input()
  layer: ILayer;

  @Input()
  legend: string;

  @Input()
  histogram: string;

  @Input()
  showTitle = true;

  @Input()
  histogramenabled: boolean;

  @Input()
  legendunit: string;

  @Input()
  histogramunit: string;

  public hideHistogramDetails = true;

  onClickHistoGram(): void {
    this.histogramenabled = !this.histogramenabled;
  }




  public getHex(color: IColor): string {
    return '#' + this.componentToHex(color.red) + this.componentToHex(color.green) + this.componentToHex(color.blue);
  }

  public getAlphaHex(color: IColor): string {
    return '#' + this.componentToHex(color.red) + this.componentToHex(color.green) + this.componentToHex(color.blue)+ this.componentToHex(color.alpha);
  }

  private componentToHex(c: number): string {
    const hex = c.toString(16);
    return hex.length === 1 ? `0${hex}` : hex;
  }

  public getPart(renderer: IRenderer, index: number): string {
    const max = renderer.band.histogram.entries.reduce((max, entry) => entry.freqency > max ? entry.freqency : max, 0);
    const scale = 65 / max;
    const part = (renderer.band.histogram.entries[index].freqency * scale) + "%";

    return part;
  }

  public getScaledValue(value:number,scale:number):number {
     let v = value;
     if(scale && scale != 0) {
       v=scale*value;
     }
     return v;
  }

  public getPercentage(renderer: IRenderer, index: number): number {
    const scale = 100 / renderer.band.histogram.entries.reduce((sum, entry) => sum + entry.freqency, 0);
    const percent = renderer.band.histogram.entries[index].freqency * scale;
    return percent < 0.1 ? null : percent;
  }

  showLegend(): boolean {
       return this.layer && this.layer.renderer && this.layer.renderer.renderType != "MULTIBAND_COLOR";
  }

  showHistogram(): boolean {
    return this.histogramenabled && this.layer.renderer.band.histogram.entries && this.layer.renderer.band.histogram.entries.length > 0 && this.layer.renderer.band.histogram.entries.length == this.layer.renderer.colorMap.entries.length;
  }

  bandContainsStatistics(): boolean {
    return this.layer.renderer.band.statistics != null;
  }
}