/*
 * 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, inject, input} from '@angular/core';
import {SCSection} from '../../../../config/profile-page-sections';
import {AuthHelperService} from '../../auth/auth-helper.service';
import {mergeMap, of} from 'rxjs';
import Swiper from 'swiper';
import {toObservable, toSignal} from '@angular/core/rxjs-interop';

@Component({
  selector: 'stapps-profile-page-section',
  templateUrl: 'profile-page-section.html',
  styleUrls: ['profile-page-section.scss'],
})
export class ProfilePageSectionComponent {
  item = input.required<SCSection>();

  minSlideWidth = input(110);

  authHelper = inject(AuthHelperService);

  loggedIn = toSignal(
    toObservable(this.item).pipe(
      mergeMap(item =>
        item.authProvider ? this.authHelper.getProvider(item.authProvider).isLoggedIn$ : of(false),
      ),
    ),
  );

  isEnd = false;

  isBeginning = true;

  slidesPerView?: number;

  slidesFillScreen = false;

  activeIndexChange(swiper: Swiper) {
    this.isBeginning = swiper.isBeginning;
    this.isEnd = swiper.isEnd;
    this.slidesFillScreen = this.slidesPerView! >= swiper.slides.length;
  }

  resizeSwiper(resizeEvent: ResizeObserverEntry, swiper: Swiper) {
    const slidesPerView =
      Math.floor((resizeEvent.contentRect.width - this.minSlideWidth() / 2) / this.minSlideWidth()) + 0.5;

    if (slidesPerView > 1 && slidesPerView !== this.slidesPerView) {
      this.slidesPerView = slidesPerView;
      swiper.params.slidesPerView = this.slidesPerView;
      swiper.update();
      this.activeIndexChange(swiper);
    }
  }

  async toggleLogIn() {
    const providerType = this.item().authProvider;
    if (!providerType) return;
    if (this.loggedIn()) {
      await this.authHelper.getProvider(providerType).signOut();
      await this.authHelper.endBrowserSession(providerType);
    } else {
      await this.authHelper.getProvider(providerType).signIn();
    }
  }
}
