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



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

  @Input() gradientItem:IItem;
  public gradientStyle:any = {};

  constructor(private ref: ChangeDetectorRef) { }

  getGradientStyle(item:IItem):any {
    if(item.data && item.data.gradient) {
      let gradient = item.data.gradient as IGradientstop[];
      let gd = '{ "background": "linear-gradient(to right,';
      for(var i=0;i<gradient.length;i++) {
        let gs = gradient[i];
        if(i>0) gd+=",";
        gd += `rgba(${gs.color.red},${gs.color.green},${gs.color.blue},${gs.color.alpha/255})`;          
        gd +=` ${gs.relativestop*100}%`
      }
      gradient.forEach((gs) => {
      });
      gd+=')"}';
      
      return JSON.parse(gd);
    }
  }

  ngOnInit(): void {
    if(this.gradientItem && this.gradientItem.itemType == "vnd.farmmaps.itemtype.gradient") {
      this.gradientStyle = this.getGradientStyle(this.gradientItem);
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if(changes['gradientItem']) {
      let gradientItem = changes['gradientItem'].currentValue;
      if(gradientItem && gradientItem.itemType == "vnd.farmmaps.itemtype.gradient") {
        this.gradientStyle = this.getGradientStyle(changes['gradientItem'].currentValue);
        this.ref.markForCheck();
      }      
    }
  }

}
