import { Component, Input,Output,ViewChild,EventEmitter, ElementRef,OnChanges,SimpleChanges,HostListener,ChangeDetectorRef, ViewEncapsulation  } 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 = false;
  @Input() public left = false;
  @Input() public extrawide: boolean;
  @Output() onResize: EventEmitter<number> = new EventEmitter<number>();
  @ViewChild("resizeGrip") elementView: ElementRef;
  public mobile = true;
  private parentHeight = 0;
  public top = "100%";
  private resizeTop=50;
  public resizing=false;

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

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

  setTop() {
    this.mobile = this.left?false: this.checkMobile();
    this.resizeTop = this.mobile?50:0;
    this.onResize.emit(this.resizeTop);
    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) {
      const 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) {
    let 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.onResize.emit(this.resizeTop);
    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'])
  handleResize(event) {
    this.setTop();
  }
}
