import { Component, OnInit, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { ModalService } from '../modal/modal.service';
import { showFromRightAnimation, showFromLeftAnimation } from './photo-gallery.animations';

@Component({
  selector: 'lib-photo-gallery',
  templateUrl: './photo-gallery.component.html',
  styleUrls: ['./photo-gallery.component.scss'],
  animations: [showFromRightAnimation, showFromLeftAnimation],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PhotoGalleryComponent implements OnInit {
  id = 'photo-gallery-modal';
  activeImage: number;
  imagesCount: number;
  @Input() productId: number;
  @Input() images: string[];
  @Input() title: string;
  rightAnimation = true;

  get currentItem() {
    return this.activeImage + 1;
  }

  constructor(private modalService: ModalService, private cdrf: ChangeDetectorRef) {}

  ngOnInit() {}

  openDialog() {
    this.modalService.open(this.id);
    this.activeImage = 0;
    this.imagesCount = this.images.length;
    this.cdrf.detectChanges();
  }

  closeModal() {
    this.modalService.close(this.id);
  }

  previousItem() {
    this.rightAnimation = false;
    if (this.imagesCount && this.activeImage === 0) {
      this.activeImage = this.imagesCount - 1;
      return;
    }
    this.activeImage--;
    this.cdrf.detectChanges();
    document.getElementById(this.activeImage.toString()).scrollIntoView();
  }

  nextItem() {
    this.rightAnimation = true;
    if (this.imagesCount && this.activeImage === this.imagesCount - 1) {
      this.activeImage = 0;
      return;
    }
    this.activeImage++;
    this.cdrf.detectChanges();
    document.getElementById(this.activeImage.toString()).scrollIntoView();
  }

  setActiveItem(index: number) {
    if (index < this.activeImage) {
      this.rightAnimation = false;
    } else {
      this.rightAnimation = true;
    }
    this.activeImage = index;
    this.cdrf.detectChanges();
  }
}
