import {AfterContentInit, Component, ContentChildren, Input, OnDestroy, QueryList} from '@angular/core';
import {SliderItemComponent} from "./slider-item.component";
import {SliderNavItemComponent} from "./slider-nav-item.component";
import {SliderContainerComponent} from "./slider-container.component";
import {LayoutService} from "../../dashboard/sharedComponents/sidebar/layout.service";
import {Subscriber} from "rxjs";

@Component({
  selector: 'slider-column',
  template: `
      <div class="uk-position-relative">
          <ng-content></ng-content>
      </div>
  `
})
export class SliderColumnComponent implements AfterContentInit, OnDestroy {
  @Input()
  type: 'slider' | 'nav' = null;
  @Input()
  animation = null;
  @ContentChildren(SliderItemComponent) items: QueryList<SliderItemComponent>;
  @ContentChildren(SliderNavItemComponent) navItems: QueryList<SliderNavItemComponent>;
  public isMobile: boolean;
  private subscriptions: any[] = [];

  constructor(private layoutService: LayoutService) {
  }

  ngOnDestroy() {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
  }

  ngAfterContentInit() {
    if (this.animation) {
      this.slides.forEach(slide => {
        slide.init(this.animation);
      });
      this.navItems.forEach(slide => {
        slide.init(this.animation);
      });
    }
    this.subscriptions.push(this.layoutService.isMobile.subscribe(isMobile => {
      this.isMobile = isMobile;
    }));
  }

  change(time: number) {
    if (this.type === 'slider') {
      let slides = this.slides;
      for (let i = 0; i < slides.length; i++) {
        slides[i].setActive(slides[i].start <= time && (!slides[i + 1] || slides[i + 1].start > time));
      }
    }
    if (this.type === 'nav') {
      let slides = this.navItems;
      for (let i = 0; i < slides.length; i++) {
        slides.get(i).setActive(!this.isMobile || (slides.get(i).start <= time && (!slides.get(i + 1) || slides.get(i + 1).start > time)));
        slides.get(i).active = slides.get(i).start <= time && (!slides.get(i + 1) || slides.get(i + 1).start > time);
      }
    }
  }

  setContainer(container: SliderContainerComponent) {
    if (this.type === 'nav') {
      this.navItems.forEach(item => {
        item.container = container;
      });
    }
  }

  get slides(): SliderItemComponent[] {
    return this.items.filter(item => item.type === 'slide');
  }
}
