import { Directive, OnDestroy, AfterViewInit, Input, ElementRef } from '@angular/core';
import { ScrollPosition, ScrollPositionService } from '../../core/services/scroll-position.service';

// tslint:disable-next-line: directive-selector
@Directive({ selector: '[rememberScrollPosition]' })
export class ScrollPositionDirective implements AfterViewInit, OnDestroy {
  @Input() key: string;

  private get ScrollPosition(): ScrollPosition {
    return {
      top: this.nativeElement.scrollTop,
      left: this.nativeElement.scrollLeft,
    };
  }

  private get nativeElement(): HTMLElement {
    return this.elementRef.nativeElement;
  }

  constructor(private elementRef: ElementRef<HTMLElement>, private scrollPositionService: ScrollPositionService) {}

  ngAfterViewInit() {
    const scrollPosition = this.scrollPositionService.getPosition(this.key);

    if (scrollPosition) {
      this.restoreScroll(scrollPosition);
    }
  }

  ngOnDestroy() {
    this.scrollPositionService.setPosition(this.key, this.ScrollPosition);
  }

  private restoreScroll({ top, left }: ScrollPosition): void {
    this.nativeElement.scroll({ top, left });
  }
}
