/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {AfterContentInit, ChangeDetectionStrategy, Component, Input, ViewContainerRef} from '@angular/core';
import {SCThings} from '@openstapps/core';
import {fromMutationObserver} from '../_helpers/rxjs/mutation-observer';
import {mergeMap, ReplaySubject, takeLast} from 'rxjs';
import {distinctUntilChanged, filter, map, startWith} from 'rxjs/operators';

/**
 * Shows a horizontal list of action chips
 */
@Component({
  selector: 'stapps-section',
  templateUrl: 'section.component.html',
  styleUrls: ['section.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SectionComponent implements AfterContentInit {
  @Input() title = '';

  @Input() item?: SCThings;

  nativeElement = new ReplaySubject<HTMLElement>(1);

  swiper = this.nativeElement.pipe(
    takeLast(1),
    mergeMap(element =>
      fromMutationObserver(element, {
        childList: true,
        subtree: true,
      }).pipe(
        startWith([]),
        map(() => element.querySelector('simple-swiper') as HTMLElement),
        distinctUntilChanged(),
        filter(element => !!element),
      ),
    ),
  );

  constructor(readonly viewContainerRef: ViewContainerRef) {}

  ngAfterContentInit() {
    this.nativeElement.next(this.viewContainerRef.element.nativeElement);
    this.nativeElement.complete();
  }
}
