/*
 * 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, OnInit} from '@angular/core';
import {Observable, of, Subscription} from 'rxjs';
import {AuthHelperService} from '../../auth/auth-helper.service';
import {SCAuthorizationProviderType, SCDateSeries, SCUserConfiguration} from '@openstapps/core';
import {ActivatedRoute} from '@angular/router';
import {ScheduleProvider} from '../../calendar/schedule.provider';
import moment from 'moment';
import {SCIcon} from '../../../util/ion-icon/icon';
import {profilePageSections} from '../../../../config/profile-page-sections';
import {filter, map} from 'rxjs/operators';

const CourseCard = {
  collapsed: SCIcon`expand_more`,
  expanded: SCIcon`expand_less`,
};

interface MyCoursesTodayInterface {
  startTime: string;
  endTime: string;
  course: SCDateSeries;
}

@Component({
  selector: 'app-home',
  templateUrl: 'profile-page.html',
  styleUrls: ['profile-page.scss'],
})
export class ProfilePageComponent implements OnInit {
  data: {
    [key in SCAuthorizationProviderType]: {loggedIn$: Observable<boolean>};
  } = {
    default: {loggedIn$: of(false)},
    paia: {loggedIn$: of(false)},
  };

  user$ = this.authHelper.getProvider('default').user$.pipe(
    filter(user => user !== undefined),
    map(userInfo => {
      return this.authHelper.getUserFromUserInfo(userInfo as object);
    }),
  );

  sections = profilePageSections;

  logins: SCAuthorizationProviderType[] = [];

  originPath: string | null;

  userInfo?: SCUserConfiguration;

  courseCardEnum = CourseCard;

  courseCardState = CourseCard.expanded;

  todayDate = moment().startOf('day').add(0, 'day').format(); // moment().startOf('day').format(); '2022-05-03T00:00:00+02:00'

  myCoursesToday: MyCoursesTodayInterface[] = [];

  subscriptions: Subscription[] = [];

  constructor(
    private authHelper: AuthHelperService,
    private route: ActivatedRoute,
    protected readonly scheduleProvider: ScheduleProvider,
  ) {}

  ngOnInit() {
    this.data.default.loggedIn$ = this.authHelper.getProvider('default').isAuthenticated$;
    this.data.paia.loggedIn$ = this.authHelper.getProvider('paia').isAuthenticated$;

    this.subscriptions.push(
      this.route.queryParamMap.subscribe(queryParameters => {
        this.originPath = queryParameters.get('origin_path');
      }),
    );

    this.getMyCourses();
  }

  async getMyCourses() {
    const uuidSubscription = this.scheduleProvider.uuids$.subscribe(async result => {
      const courses = await this.scheduleProvider.getDateSeries(result);

      for (const course of courses.dates) {
        for (const date of course.dates) {
          if (moment(date).startOf('day').format() === this.todayDate) {
            this.myCoursesToday[this.myCoursesToday.length] = {
              startTime: moment(date).format('LT'),
              endTime: moment(date).add(course.duration).format('LT'),
              course,
            };
          }
        }
      }
      uuidSubscription.unsubscribe();
    });
  }

  async signIn(providerType: SCAuthorizationProviderType) {
    await this.handleOriginPath();
    this.authHelper.getProvider(providerType).signIn();
  }

  async signOut(providerType: SCAuthorizationProviderType) {
    await this.authHelper.getProvider(providerType).signOut();
    this.userInfo = undefined;
  }

  toggleCourseCardState() {
    if (this.courseCardState === CourseCard.expanded) {
      const card: HTMLElement | null = document.querySelector('.course-card');
      const height = card?.scrollHeight;
      if (card && height) {
        card.style.setProperty('--max-height', height + 'px');
      }
    }

    this.courseCardState =
      this.courseCardState === CourseCard.expanded ? CourseCard.collapsed : CourseCard.expanded;
  }

  private async handleOriginPath() {
    this.originPath
      ? await this.authHelper.setOriginPath(this.originPath)
      : await this.authHelper.deleteOriginPath();
  }

  ionViewWillEnter() {
    this.authHelper
      .getProvider('default')
      .getValidToken()
      .then(() => void this.authHelper.getProvider('default').loadUserInfo())
      .catch(() => {
        // noop
      });
    this.authHelper
      .getProvider('paia')
      .getValidToken()
      .catch(() => {
        // noop
      });
  }
}
