import { Component, ChangeDetectorRef, Input,SimpleChanges,OnChanges, Output,EventEmitter } from '@angular/core';
import { IItem } from '../../models/item';

@Component({
    selector: 'fm-gradient-select',
    templateUrl: './gradient-select.component.html',
    styleUrls: ['./gradient-select.component.scss'],
    standalone: false
})
export class GradientSelectComponent implements OnChanges {

  public listVisible = false;
  @Input() showLabel = true;
  @Input() gradientItems:IItem[];
  @Input() showAdd = false;
  @Input() selectedItem:IItem;
  @Output() onSelect:EventEmitter<any> = new EventEmitter<any>();
  @Output() onAdd:EventEmitter<MouseEvent> = new EventEmitter<MouseEvent>();


  constructor(private ref:ChangeDetectorRef) {   
  }

   ngOnChanges(changes:SimpleChanges) {
      if(changes["gradientItems"]) {
        this.gradientItems=changes["gradientItems"].currentValue;
        this.selectedItem=this.selectedItem == null && this.gradientItems && this.gradientItems.length>0?this.gradientItems[0]:null;
        this.ref.detectChanges();
      }     
  }

  handleToggleList() {
    this.listVisible=!this.listVisible;
  }

  handleSelect(item:IItem) {
    this.selectedItem=item;
    this.onSelect.emit(item);
  }

  handleAdd(event:MouseEvent) {
    event.preventDefault();
    this.onAdd.emit(event);
  }

  isSelected(item:IItem):boolean {
    if(this.selectedItem && this.selectedItem.data  && this.selectedItem.data.gradient && item && item.data && item.data.gradient) {
       const sid = JSON.stringify(this.selectedItem.data.gradient)+this.selectedItem.name;
       const id = JSON.stringify( item.data.gradient) + item.name;
       return sid == id;
    }
    return false;
  }

}
