import { Component, Input, AfterViewInit, ViewChild } from '@angular/core';
import { Feature} from 'ol';
import { Geometry,Polygon,MultiPolygon } from 'ol/geom';
import * as extent from 'ol/extent';
import * as render from 'ol/render';
import * as style from 'ol/style';

@Component({
  selector: 'fm-map-feature-thumbnail',
  templateUrl: './feature-thumbnail.component.html',
  styleUrls: ['./feature-thumbnail.component.scss']
})
export class GeometryThumbnailComponent implements AfterViewInit {


  constructor() { }

  @ViewChild('canvas') canvas;
  @ViewChild('container') container;

  private geometry:Geometry = null;
  @Input() set feature(value:Feature<Geometry>) {
    if(value) {
      this.geometry = value.getGeometry();
    } else {
      this.geometry = null;
    }
    this.render(this.canvas,
      this.geometryStyle,
      this.geometry,
      this.width, 
      this.height);
  }

  private defaultStyle:style.Style = new style.Style({
    stroke: new style.Stroke({ color: 'black',width:1.5 })
  });  
  private geometryStyle:style.Style = this.defaultStyle;
  @Input() set fillColor(value:string) {
    if(style) {
      this.geometryStyle = new style.Style({
        stroke: new style.Stroke({ color: 'black',width:1.5 }),
        fill: new style.Fill({color: value})
      });  
    } else {
      this.geometryStyle = this.defaultStyle
    }
    this.render(this.canvas,
      this.geometryStyle,
      this.geometry,
      this.width, 
      this.height);
  }

  private width = 0;
  private height = 0;

  render(canvas,style:style.Style,geometry:Geometry,width:number,height:number) {  
    if(canvas && canvas.nativeElement && geometry && style) {
      const renderContext = render.toContext(canvas.nativeElement.getContext( '2d'),{ size: [width, height] });  

      const geom   = geometry.clone() as Polygon,
      line   = geom.getCoordinates()[0],
      e = extent.boundingExtent( line );
  
      const dxy = extent.getCenter(e),
      sxy = [ 
          (width - 2 ) / extent.getWidth(e),
          (height - 2 ) / extent.getHeight(e)
      ];
  
      const dx = dxy[0], 
          dy = dxy[1],
          sx = sxy[0],
          sy = sxy[1];
  
      geom.translate( -dx, -dy );
      geom.scale( Math.min(sx, sy), -Math.min(sx, sy));
      geom.translate(width / 2,height / 2 );
      renderContext.setStyle( style );  
      renderContext.drawGeometry( geom );
    }
  }

  ngAfterViewInit() {
    this.width = this.container.nativeElement.offsetWidth;
    this.height = this.container.nativeElement.offsetHeight;
    this.render(this.canvas,
      this.geometryStyle,
      this.geometry,
      this.width, 
      this.height);
  }  

}
