import {ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, 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 { CookieService } from 'ngx-cookie-service';
import {HeaderComponent} from '../../components/header/header.component';
import {Router} from '@angular/router';
import {FooterComponent} from '../../components/footer/footer.component';

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

  constructor(private authorService: AuthorService,
              private messageService: MessageService,
              private cookieService: CookieService,
              private router: Router) {}

  sendLogins(): void {
    if (this.password === this.confirmPassword) {
      this.subs.push
      (
        this.authorService.login(this.name, this.password).pipe(
          switchMap((tokenObj: any) => {
            this.cookieService.set("token", tokenObj.token);
            return this.authorService.me(tokenObj.token)
          }))
          .subscribe({
            next: (author: Author) => {
              console.log(author)
              this.cookieService.set("author", JSON.stringify(author), {path: '/'});
              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.message)
          })
      );
    } else {
      this.failureMessage('Erreur de connexion', 'Les deux mots de passe ne correspondent pas')
    }
  }

  getAuthorCookie(): void {
    this.actualAuthor = JSON.parse(this.cookieService.get("author"));
  }

  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());
  }

}
