/*
 * 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, Input, OnDestroy, 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, Subscription} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import {DataRoutingService} from '../data-routing.service';
import {NavController} from '@ionic/angular';

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

  $width: Observable<number>;

  subscriptions: Subscription[] = [];

  @Input() autoRouting = true;

  @Input() maxItems = 2;

  @Input() set item(item: SCThings) {
    // eslint-disable-next-line unicorn/prefer-ternary
    if (item.type === SCThingType.Catalog && item.superCatalogs) {
      this.path = new Promise(resolve =>
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        resolve([...item.superCatalogs!, item]),
      );
    } else if (item.type === SCThingType.Assessment && item.superAssessments) {
      this.path = new Promise(resolve =>
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        resolve([...item.superAssessments!, item]),
      );
    } else if (
      item.type === SCThingType.AcademicEvent &&
      item.catalogs &&
      (item.catalogs.length === 1 || this.routeStack.lastDataDetail)
    ) {
      const catalogWithoutReferences = item.catalogs[0];
      const catalogPromise = (
        item.catalogs.length === 1
          ? this.dataProvider.get(catalogWithoutReferences.uid, DataScope.Remote)
          : this.routeStack.lastDataDetail
      ) as Promise<SCCatalog>;

      this.path = new Promise(async resolve => {
        const catalog = await catalogPromise;
        const superCatalogs = catalog.superCatalogs;

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

  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.subscriptions.push(
      this.dataRoutingService.pathSelectListener().subscribe(item => {
        void this.navController.navigateBack(['data-detail', item.uid]);
      }),
    );
  }

  ngOnDestroy() {
    for (const sub of this.subscriptions) sub.unsubscribe();
  }
}
