import { Component, OnInit, ViewChildren, QueryList, Input, AfterViewInit, ContentChildren, AfterContentInit, OnDestroy } from '@angular/core';
import { AccordinTabCustomComponent } from './accordin-tab-custom/accordin-tab-custom.component';
@Component({
  selector: 'accordin-custom',
  templateUrl: './accordin-custom.component.html',
  styleUrls: ['./accordin-custom.component.scss'],
})
export class AccordinCustomComponent implements OnInit {
  @ContentChildren(AccordinTabCustomComponent) tabs !: QueryList<AccordinTabCustomComponent>;
  @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: AccordinTabCustomComponent, index) => {
      item.setAccordion(this);
      if (index === this.activeIndex) {
        setTimeout(() => {
          if (!this.destroyed) {
            item.setVisibility(true);
          }
        }, 200);
      }
    });
  }

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

}
