import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {UserService} from "../../services/auth/user.service";
import {Router} from "@angular/router";
import {RoutePath} from "../../enum/route-path";
import { UserInformation } from 'src/app/models/user-information';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {

  @ViewChild('loginDiv') cardContainer: ElementRef | null = null;

  username: string | null = null;
  password: string | null = null;

  isAnimating = false;
  loginFailed = false;

  constructor(
    private userService: UserService,
    private router: Router,
  ) {
    this.userService.setAuthenticationToken(null);
  }

  login() {
    this.userService.login(this.username!, this.password!)
      .subscribe({
        next: (loginResult: any) => {
          console.log(loginResult)
          this.cardContainer!.nativeElement.classList = `login__block active animate__animated animate__flipOutX`;
          this.userService.setAuthenticationToken(loginResult.authenticationToken);

          this.userService.getUserDetails(this.username!)
            .subscribe({next: (userInformation: UserInformation) => {
                localStorage.setItem('userInformation', JSON.stringify(userInformation));
              }
            })

          setTimeout(() => {this.router.navigate([RoutePath.SLASH]);}, 900)

        },
        error: (error: any) => {
          this.bounceCard();
          this.loginFailed = true;
          console.error(error);
        }
      })
  }

  bounceCard(): void {
    this._animate('shakeX').catch((e) => {
      console.error('Error animating element:', e);
    });
  }

  private _animate(animationName: string, persistClass = false): Promise<void> {
    if (!this.cardContainer || !this.cardContainer.nativeElement) {
      return Promise.reject('element not defined');
    }

    if (this.isAnimating) {
      return Promise.reject('element is animating');
    }
    return new Promise((resolve) => {
      this.isAnimating = true;

      // listen to animationend to allow additional logic to be run
      // after the animation from Animate.css is done executing
      this.cardContainer!.nativeElement.addEventListener(
        'animationend',
        (event:any) => {
          if (event.animationName === animationName) {
            this.isAnimating = false;
            if (!persistClass) {
              this.cardContainer!.nativeElement.classList = 'login__block active';
            }
            resolve();
          }
        },
        { once: true }
      );
      this.cardContainer!.nativeElement.classList = `login__block active animate__animated animate__${animationName}`;
    });
  }



  ngOnInit(): void {
  }

}
