/*
 * Copyright (C) 2022 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, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {AssessmentsProvider} from '../assessments.provider';
import {DataDetailComponent, ExternalDataLoadEvent} from '../../data/detail/data-detail.component';
import {NavController} from '@ionic/angular/standalone';
import {DataRoutingService} from '../../data/data-routing.service';
import {SCAssessment} from '@openstapps/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Component({
  selector: 'assessments-detail',
  templateUrl: 'assessments-detail.html',
  styleUrls: ['assessments-detail.scss'],
})
export class AssessmentsDetailComponent implements OnInit {
  destroy$ = inject(DestroyRef);

  constructor(
    readonly route: ActivatedRoute,
    readonly assessmentsProvider: AssessmentsProvider,
    readonly dataRoutingService: DataRoutingService,
    readonly navController: NavController,
    readonly activatedRoute: ActivatedRoute,
  ) {}

  @Input() dataPathAutoRouting = true;

  @ViewChild(DataDetailComponent)
  detailComponent: DataDetailComponent;

  item: SCAssessment;

  ngOnInit() {
    if (!this.dataPathAutoRouting) return;
    this.dataRoutingService
      .pathSelectListener()
      .pipe(takeUntilDestroyed(this.destroy$))
      .subscribe(item => {
        void this.navController.navigateBack(['assessments', 'detail', item.uid], {
          queryParams: {
            token: this.activatedRoute.snapshot.queryParamMap.get('token'),
          },
        });
      });
  }

  getItem(event: ExternalDataLoadEvent) {
    this.assessmentsProvider
      .getAssessment(event.uid, this.route.snapshot.queryParamMap.get('token'), event.forceReload)
      .then(assessment => {
        this.item = assessment;
        event.resolve(this.item);
      });
  }
}
