import { Component, OnInit, ViewChildren, QueryList, Input, AfterViewInit, ContentChildren, AfterContentInit, OnDestroy } from '@angular/core';
import { AccordionTabComponent } from './accordion-tab/accordion-tab.component';

@Component({
  selector: 'accordion',
  templateUrl: './accordion.component.html',
  styleUrls: ['./accordion.component.scss'],
})
export class AccordionComponent implements OnInit, AfterContentInit, OnDestroy {
  @ContentChildren(AccordionTabComponent) tabs !: QueryList<AccordionTabComponent>;
  @Input() activeIndex: number;
  private destroyed = false;
  constructor() { }

  ngOnInit() {

  }

  ngOnDestroy(): void {
    this.destroyed = true;
  }
  ngAfterContentInit() {
    this.tabs.notifyOnChanges();
    this.tabs.changes.subscribe(() => {
      this.processChildren();
    });
    this.processChildren();
  }

  private processChildren() {
    // this.tabs.notifyOnChanges();
    this.tabs.forEach((item: AccordionTabComponent, index) => {
      item.setAccordion(this);
      if (index === this.activeIndex) {
        setTimeout(() => {
          if (!this.destroyed) {
            item.setVisibility(true);
          }
        }, 200);
      }
    });
  }

  public tabClicked(clickedTab: AccordionTabComponent) {
    this.tabs.forEach((tab: AccordionTabComponent) => {
      if (tab !== clickedTab) {
        tab.setVisibility(false);
      } else {
      }
    });
  }

}
