import {Component, OnDestroy, OnInit} from '@angular/core';
import {UntypedFormBuilder, UntypedFormGroup, Validators} from '@angular/forms';
import {switchMap} from 'rxjs/operators';
import {of, Subscription} from 'rxjs';
import {AuthService} from '../../auth/services/auth.service';
import {Router} from '@angular/router';

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

  loginForm: UntypedFormGroup;
  subscription: Subscription[] = [];

  constructor(
    private formBuilder: UntypedFormBuilder,
    private authService: AuthService,
    private router: Router
  ) {
  }

  /**
   * Unsubscribe after leaving
   */
  ngOnDestroy(): void {
    this.subscription.forEach(subs => subs.unsubscribe());
  }

  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      username: ['', [Validators.required]],
      password: ['', Validators.required]
    });
    this.userRedirect();
  }

  /**
   * Process login
   */
  doLogin(): void {
    if (this.loginForm.valid) {
      const username = this.loginForm.controls.username.value;
      const password = this.loginForm.controls.password.value;
      this.subscription[2] = this.authService.doLogin({username, password})
        .pipe(
          switchMap(res => {
            if (res) {
              console.log('Login getUserState');
              return this.authService.getUserState();
            } else {
              return of(false);
            }
          })
        ).subscribe(res => {
            if (res) {
              this.subscription[2].unsubscribe();
              this.router.navigate(['/dashboard'])
            }
          }
        );
    }
  }

  /**
   * If user already logged with valid sessionId redirect to dashboard
   */
  userRedirect(): void {
    console.log('Login redirect');
    if (this.authService.getUser()){
      this.router.navigate(['/dashboard']);
    }
  }
}
