import {Component, Input} from '@angular/core';
import {ObjectsService} from "@app/_services";
import SwiperCore, {Navigation, Pagination, SwiperOptions} from 'swiper';
SwiperCore.use([Navigation, Pagination]);

@Component({
  selector: 'images-section',
  templateUrl: 'images-section.component.html',
  styleUrls: ['images-section.component.scss']
})
export class ImagesSectionComponent {
  @Input() section: any;

  public config: SwiperOptions;

  public parsedPhotos: any[] = []
  public activePhoto: string = ''
  public nextId:string;
  public backId:string;
  public showId: string = ''
  public showFullscreen = false;
  public activeIndex: number = 0
  public tmpNumber: number = 0

  constructor(private objectsService: ObjectsService) {
  }


  ngOnInit() {
    this.config = {
      slidesPerView: 1,
      spaceBetween: 40,
      navigation: {prevEl: `#section-${this.section?.id} .prev`, nextEl: `#section-${this.section?.id} .next`}
    }

    setTimeout(()=>{
      this.parsed();
    }, 300)
  }


  get items() {
    return this.objectsService.getValue(this.section, 'images-required');
  }
  get imageType() {
    let type = this.objectsService.getValue(this.section, 'image-type');
    return type.name;
  }
  set photo(activePhoto: string) {
    this.activePhoto = activePhoto
  }
  get photo(): string {
    return this.activePhoto
  }


  parsed(): void {
    this.tmpNumber = 0
    this.parsedPhotos = this.items || []
    this.parsedPhotos.map((photo: any) => {
      if (this.tmpNumber===0) {
        photo.active = true
        this.photo = photo.links.full
        this.showId = photo.id
      } else {
        photo.active = false
        if (this.tmpNumber===1) {
          this.nextId = photo.id
        }
      }
      this.tmpNumber++
      if (this.items.length > 1 && this.items.length == this.tmpNumber) {
        this.backId = photo.id
      }
      return photo
    })
  }

  show(id: string): void {
    this.parsedPhotos?.forEach((photo: any) => {
      if (photo.id === id) {
        this.photo = photo.links.full
        this.showFullscreen = true
      }
    })
  }

  go(how: string) {
    this.show(this.showId)
    switch(how) {
      case 'decrement':
        this.activeIndex--
        if (this.activeIndex < 0) this.activeIndex = this.parsedPhotos.length - 1
        break
      case 'increment':
        this.activeIndex++
        if (this.activeIndex == this.parsedPhotos.length) this.activeIndex = 0
        break
    }
    this.parsedPhotos = this.parsedPhotos.map((item: any, index: number) => {
      if (index === this.activeIndex) {
        item.active = true
        this.photo = item.links.full
        this.showId = item.id
      } else {
        item.active = false
      }
      return item
    })
  }
}
