/*
 * 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 {AfterViewInit, Component, DestroyRef, inject, OnInit, ViewChild} from '@angular/core';
import {AssessmentsProvider} from '../assessments.provider';
import {SCAssessment, SCCourseOfStudy} from '@openstapps/core';
import {ActivatedRoute, Router} from '@angular/router';
import {NGXLogger} from 'ngx-logger';
import {materialSharedAxisX} from '../../../animation/material-motion';
import {SharedAxisChoreographer} from '../../../animation/animation-choreographer';
import {DataProvider, DataScope} from '../../data/data.provider';
import {DataRoutingService} from '../../data/data-routing.service';
import {groupBy, mapValues} from '@openstapps/collection-utils';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-assessments-page',
  templateUrl: 'assessments-page.html',
  styleUrls: ['assessments-page.scss'],
  animations: [materialSharedAxisX],
})
export class AssessmentsPageComponent implements OnInit, AfterViewInit {
  assessments: Promise<
    Record<
      string,
      {
        assessments: SCAssessment[];
        courseOfStudy: Promise<SCCourseOfStudy | undefined>;
      }
    >
  >;

  assessmentKeys: string[] = [];

  @ViewChild('segment') segmentView!: HTMLIonSegmentElement;

  sharedAxisChoreographer: SharedAxisChoreographer<string> = new SharedAxisChoreographer<string>('', []);

  destroy$ = inject(DestroyRef);

  constructor(
    readonly logger: NGXLogger,
    readonly assessmentsProvider: AssessmentsProvider,
    readonly dataProvider: DataProvider,
    readonly activatedRoute: ActivatedRoute,
    readonly dataRoutingService: DataRoutingService,
    readonly router: Router,
  ) {}

  ngAfterViewInit() {
    this.segmentView.value = this.sharedAxisChoreographer.currentValue;
  }

  ngOnInit() {
    this.dataRoutingService
      .itemSelectListener()
      .pipe(takeUntilDestroyed(this.destroy$))
      .subscribe(thing => {
        void this.router.navigate(['assessments', 'detail', thing.uid], {
          queryParams: {
            token: this.activatedRoute.snapshot.queryParamMap.get('token'),
          },
          state: {item: thing},
        });
      });

    this.activatedRoute.queryParams.subscribe(parameters => {
      try {
        this.assessments = this.assessmentsProvider
          .getAssessments(parameters.token)
          .then(assessments => groupBy(assessments, it => it.courseOfStudy?.uid ?? 'unknown'))
          .then(it => {
            this.assessmentKeys = Object.keys(it);
            this.sharedAxisChoreographer = new SharedAxisChoreographer(
              this.assessmentKeys[0],
              this.assessmentKeys,
            );
            if (this.segmentView) {
              this.segmentView.value = this.sharedAxisChoreographer.currentValue;
            }
            return it;
          })
          .then(groups =>
            mapValues(groups, (group, uid) => ({
              assessments: group,
              courseOfStudy: this.dataProvider
                .get(uid, DataScope.Remote)
                .catch(() => group[0].courseOfStudy) as Promise<SCCourseOfStudy>,
            })),
          );
      } catch (error) {
        this.logger.error(error);
        this.assessments = Promise.resolve({});
      }
    });
  }
}
