/*
 * 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 {Component, DestroyRef, inject, Input, OnInit} from '@angular/core';
import {RoutingStackService} from '../../../util/routing-stack.service';
import {SCCatalog, SCThings, SCThingType, SCThingWithoutReferences} from '@openstapps/core';
import {DataProvider, DataScope} from '../data.provider';
import {fromEvent, Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import {DataRoutingService} from '../data-routing.service';
import {NavController} from '@ionic/angular/standalone';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Component({
  selector: 'stapps-data-path',
  templateUrl: './data-path.html',
  styleUrls: ['./data-path.scss'],
})
export class DataPathComponent implements OnInit {
  path: Promise<SCThingWithoutReferences[]>;

  $width: Observable<number>;

  @Input() autoRouting = true;

  @Input() maxItems?: number = 2;

  @Input() set item(item: SCThings) {
    if (item.type === SCThingType.Catalog && item.superCatalogs) {
      this.path = Promise.resolve([...item.superCatalogs!, item]);
    } else if (item.type === SCThingType.Assessment && item.superAssessments) {
      this.path = Promise.resolve([...item.superAssessments!, item]);
    } else if (
      item.type === SCThingType.AcademicEvent &&
      item.catalogs &&
      (item.catalogs.length === 1 || this.routeStack.lastDataDetail)
    ) {
      this.path = new Promise(async resolve => {
        const catalogWithoutReferences = item.catalogs![0];
        const catalog =
          item.catalogs!.length === 1
            ? await this.dataProvider.get(catalogWithoutReferences.uid, DataScope.Remote)
            : this.routeStack.lastDataDetail;
        const superCatalogs = (catalog as SCCatalog).superCatalogs;

        resolve(
          superCatalogs
            ? [...superCatalogs, catalogWithoutReferences, item]
            : [catalogWithoutReferences, item],
        );
      });
    }
  }

  destroy$ = inject(DestroyRef);

  constructor(
    readonly dataRoutingService: DataRoutingService,
    readonly navController: NavController,
    readonly routeStack: RoutingStackService,
    readonly dataProvider: DataProvider,
  ) {}

  ngOnInit() {
    this.$width = fromEvent(window, 'resize').pipe(
      map(() => window.innerWidth),
      startWith(window.innerWidth),
    );

    if (!this.autoRouting) return;
    this.dataRoutingService
      .pathSelectListener()
      .pipe(takeUntilDestroyed(this.destroy$))
      .subscribe(item => {
        void this.navController.navigateBack(['data-detail', item.uid]);
      });
  }
}
