import { DOCUMENT } from '@angular/common';
import { AfterViewInit, Directive, ElementRef, HostListener, Inject, Input, OnDestroy, Renderer2, Type } from '@angular/core';
import { AppDragDropService } from './app-drag-drop.service';

@Directive({
  selector: '[appDropList]'
})
export class DropListDirective implements OnDestroy, AfterViewInit {

  public static SCROLL_PLACE_SENSITIVITY = 20;
  @Input('appDropList') dropZone; 

  /**
   * Unique id. Drag directive checks this to decide to recreate its preview or not
   */
  @Input('appDropListId') dropListId?; 
  
  /**
   * Name of the component class. You have to predifine it in the appDragDropService previewClasses config
   */
  @Input('appPreviewComponentType') previewComponentType?: string = null; 
  
  /**
   * Behavior as a callback how to resolve the component. Passing paramteres, etc.
   * cb auto parameters: (componentRef)=>{}
   */
  @Input('appPreviewResolver') previewResolver? = null;

  public onMouseMove: any;

  constructor(private renderer: Renderer2, private el: ElementRef, @Inject(DOCUMENT) private document: Document, private appDragDropService: AppDragDropService) {
    this.appDragDropService.registerDropList(this);

    this.onMouseMove = (event)=>{
      
      if (this.appDragDropService.isDragOn()){
        let bond = this.getDOMNode().getBoundingClientRect();
        if (event.clientY > bond.top && event.clientY < bond.top + DropListDirective.SCROLL_PLACE_SENSITIVITY){
          this.scroll(0, -50);
        }
        else if (event.clientY < bond.top + bond.height && event.clientY > bond.top + bond.height - DropListDirective.SCROLL_PLACE_SENSITIVITY){
          this.scroll(0, 50);
        }
      }
    }
  }

 

  public ngAfterViewInit(){
    this.getDOMNode().dataset.appDropListId = this.dropListId;
  }

  public getDropListId(){
    return this.dropListId;
  }

  public getDropZone(){
    return this.dropZone;
  }

  public getDOMNode(): HTMLElement{
    return this.el.nativeElement;
  }

  private scroll(left, top){
    this.getDOMNode().scrollBy({
      top: top,
      left: left,
      behavior: 'smooth'
    });
  }

  ngOnDestroy() {
    this.appDragDropService.deregisterDropList(this)
  }

}
