import {Component, OnDestroy} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {Button} from 'primeng/button';
import {AuthorService} from '../../services/author.service';
import {ToastModule} from 'primeng/toast';
import {MessageService} from 'primeng/api';
import {Author} from '../../models/author';
import {Subscription, switchMap} from 'rxjs';
import {HeaderComponent} from '../../components/header/header.component';
import {Router} from '@angular/router';
import {ConfigurationService} from '../../configuration.service';
import {DateTime} from 'luxon';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [
    FormsModule,
    InputTextModule,
    Button,
    ToastModule,
    HeaderComponent,
  ],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent implements OnDestroy {
  name: string = "";
  actualAuthor: Author | undefined;
  password: string = "";
  subs: Subscription[] = [];

  constructor(private authorService: AuthorService,
              private messageService: MessageService,
              private router: Router,
              private configurationService: ConfigurationService,) {
  }

  sendLogins(): void {
    this.subs.push
    (
      this.authorService.login(this.name, this.password).pipe(
        switchMap((tokenObj: any) => {
          // sessionStorage.removeItem('token');
          sessionStorage.setItem('token', tokenObj.token);
          return this.authorService.me(tokenObj.token)
        }))
        .subscribe({
          next: (author: Author) => {
            // sessionStorage.removeItem('author');
            sessionStorage.setItem('author', JSON.stringify(author));
            sessionStorage.setItem('token-expiration-date', DateTime.now().plus({millisecond: this.configurationService.getTokenTTL()}).toISO())
            this.getAuthorCookie();
            this.router.navigate(['/']).then(() => {
              this.successMessage('Connecté avec succès', 'Heureux de vous revoir ' + this.actualAuthor?.name)
            });
          },
          error: (err) => this.failureMessage('Erreur de connexion', err.error.message)
        })
    );
  }

  getAuthorCookie(): void {
    const authorStr = sessionStorage.getItem('author');
    if (authorStr) {
      this.actualAuthor = JSON.parse(authorStr);
    }
  }

  successMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'success',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  failureMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'error',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  ngOnDestroy(): void {
    this.subs.forEach(sub => sub.unsubscribe());
  }

}
