import { Component, Input,ViewChild,ElementRef,OnChanges,SimpleChanges,HostListener,ChangeDetectorRef  } from '@angular/core';

@Component({
  selector: 'fm-side-panel',
  templateUrl: 'side-panel.component.html',
  styleUrls: ['side-panel.component.scss']
})


export class SidePanelComponent  implements OnChanges {
  @Input() public visible: boolean;
  @Input() public collapsed: boolean;
  @Input() public collapsable: boolean;
  @Input() public resizeable: boolean = false;
  @Input() public left: boolean = false;
  @ViewChild("resizeGrip") elementView: ElementRef;
  public mobile:boolean = true;
  private parentHeight:number = 0;
  public top = "100%";
  private resizeTop:number=50;
  public resizing:boolean=false;

  constructor(private element: ElementRef,private ref: ChangeDetectorRef) {
    this.collapsable = false;
    this.setTop();
  }

  checkMobile():boolean {
    let size = parseFloat(getComputedStyle(document.documentElement).width);
    let rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
    let threshold = 40 * rem;
    return !(size>threshold);
  }

  setTop() {
    this.mobile = this.left?false: this.checkMobile();
    this.resizeTop = this.mobile?50:0;
    this.top =  (this.visible?this.resizeTop: (this.mobile? 100:0)) + "%";
  }

  ngAfterViewInit() {
    this.parentHeight = this.element.nativeElement.offsetParent.clientHeight;
    this.setTop();
  }

  handleToggleClick(event) {
    if (this.collapsable) {
      this.collapsed = !this.collapsed;     
    }
  }

  handleStartGripDrag(event:DragEvent|TouchEvent) {
    this.resizing=true;
    if(event instanceof DragEvent) {
      var crt = new Image();
      crt.style.display = "none"; 
      document.body.appendChild(crt);
      event.dataTransfer.setDragImage(crt,0,0);
    }   
  }

  handleEndGripDrag() {
    this.resizing = false;
  }

  handleGripDrag(event:DragEvent|TouchEvent) {
    var clientY = 0;
    if((event instanceof TouchEvent)) {
      clientY = (event as TouchEvent).changedTouches[0].clientY;
    } else {
      clientY=(event as DragEvent).clientY;
    }
    this.resizeTop =  Math.min(98, Math.max(0, clientY / (this.parentHeight  / 100)));
    this.top =  (this.visible? this.resizeTop:(this.mobile? 100:0)) + "%";
  }

  ngOnChanges(changes: SimpleChanges) {
    if(changes.visible) {
      this.top =  (changes.visible.currentValue?this.resizeTop:(this.mobile? 100:0)) + "%";
    }    
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.setTop();
  }
}
