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




@Component({
  selector: 'app-slider',
  templateUrl: './slider.component.html',
  styleUrls: ['./slider.component.css']
})
export class SliderComponent implements OnInit {
  @Input() startPosition?: number;
  @Input() valueStep?: number;
  @ViewChild('contentLeft') elementContentData: ElementRef;
  public valueLeftContentSlide: number;
  private position: number;
  ngOnInit() {
    this.valueStep = this.valueStep || 100;
    this.valueLeftContentSlide = (this.startPosition || 0);
    this.elementContentData.nativeElement.style.left = this.valueLeftContentSlide + 'px';

    this.dragElement();
  }
  slideArrow(direction) {

    let left = parseInt(this.elementContentData.nativeElement.style.left, 0);
    left = isNaN(left) ? 0 : left;
    if (direction === 'right') {

      this.elementContentData.nativeElement.style.left = left + this.valueStep + 'px';

    } else if (direction === 'left') {
      this.elementContentData.nativeElement.style.left = left - this.valueStep + 'px';
    }
    this.valueLeftContentSlide = parseInt(this.elementContentData.nativeElement.style.left, 0);
  }

  private dragElement() {
    let pos1 = 0, pos2 = 0;
    const transition = this.elementContentData.nativeElement.style.transition;

    const dragMouseDown = (e) => {
      e.stopPropagation();
      e = e || window.event;
      this.elementContentData.nativeElement.style.transition = 'none';
      // get the mouse cursor position at startup:
      pos2 = e.clientX;


      // call a function whenever the cursor moves:
      this.elementContentData.nativeElement.onmousemove = elementDrag;
      this.valueLeftContentSlide = parseInt(this.elementContentData.nativeElement.style.left, 0);
    };

    const elementDrag = (e) => {
      e.stopPropagation();
      e = e || window.event;
      // calculate the new cursor position:
      pos1 = pos2 - e.clientX;

      pos2 = e.clientX;

      this.elementContentData.nativeElement.style.left = (parseInt(this.elementContentData.nativeElement.style.left, 0) - pos1) + 'px';
      this.valueLeftContentSlide = parseInt(this.elementContentData.nativeElement.style.left, 0);
    };

    const closeDragElement = () => {

      /* stop moving when mouse button is released:*/
      // this.elementContentData.nativeElement.onmouseup = null;
      this.elementContentData.nativeElement.onmousemove = null;

      this.elementContentData.nativeElement.style.transition = transition;
      this.valueLeftContentSlide = parseInt(this.elementContentData.nativeElement.style.left, 0);
    };

    this.elementContentData.nativeElement.onmouseup = closeDragElement;
    this.elementContentData.nativeElement.onmouseout = closeDragElement;
    this.elementContentData.nativeElement.onmouseleave = closeDragElement;
    this.elementContentData.nativeElement.onmousedown = dragMouseDown;
  }

}


