/*
 * 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 {SCSection} from '../../../../config/profile-page-sections';
import {AuthHelperService} from '../../auth/auth-helper.service';
import {Observable, Subscription} from 'rxjs';
import {SCAuthorizationProviderType} from '@openstapps/core';
import Swiper from 'swiper';
import {AlertController} from '@ionic/angular';
import {TranslateService} from '@ngx-translate/core';

@Component({
  selector: 'stapps-profile-page-section',
  templateUrl: 'profile-page-section.html',
  styleUrls: ['profile-page-section.scss'],
})
export class ProfilePageSectionComponent implements OnInit, OnDestroy {
  @Input() item: SCSection;

  @Input() minSlideWidth = 110;

  isLoggedIn: boolean;

  isEnd = false;

  isBeginning = true;

  subscriptions: Subscription[] = [];

  slidesPerView: number;

  slidesFillScreen = false;

  data: {
    [key in SCAuthorizationProviderType]: {loggedIn$: Observable<boolean>};
  } = {
    default: {
      loggedIn$: this.authHelper.getProvider('default').isAuthenticated$,
    },
    paia: {
      loggedIn$: this.authHelper.getProvider('paia').isAuthenticated$,
    },
  };

  constructor(
    private authHelper: AuthHelperService,
    private alertController: AlertController,
    private translateService: TranslateService,
  ) {}

  ngOnInit() {
    if (this.item.authProvider) {
      this.subscriptions.push(
        this.data[this.item.authProvider].loggedIn$.subscribe(loggedIn => {
          this.isLoggedIn = loggedIn;
        }),
      );
    }
  }

  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() {
    if (!this.item.authProvider) return;
    await (this.isLoggedIn ? this.signOut(this.item.authProvider) : this.signIn(this.item.authProvider));
  }

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

  async signOut(providerType: SCAuthorizationProviderType) {
    await this.authHelper.getProvider(providerType).signOut();

    const alert: HTMLIonAlertElement = await this.alertController.create({
      header: this.translateService.instant(`auth.messages.${providerType}.log_out_alert.header`),
      message: this.translateService.instant(`auth.messages.${providerType}.log_out_alert.message`),
      buttons: [
        {
          text: this.translateService.instant('no'),
          cssClass: 'default',
        },
        {
          text: this.translateService.instant('yes'),
          role: 'confirm',
          cssClass: 'preferred',
          handler: () => {
            this.authHelper.endBrowserSession(providerType);
          },
        },
      ],
    });

    await alert.present();
  }

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