import {Component, OnDestroy, OnInit} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
import {Actions, ofActionCompleted, Store} from '@ngxs/store';
import {LoginAction, LogoutAction, UserState} from '../../states/user.state';
import {Router} from '@angular/router';
import {MessageService} from "primeng/api";
import {LoginService} from "../../service/login.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  public loginForm = new FormGroup({
    username: new FormControl(),
    password: new FormControl(),
  });
  display:boolean = false;
  email:string = "";
  // tslint:disable-next-line:max-line-length
  constructor(private action: Actions, private router: Router, private messageService: MessageService, private store: Store, private loginService:LoginService) { }
  ngOnInit() {
    this.action.pipe(ofActionCompleted(LoginAction)).subscribe(res => {
      if (res.result.error) {
        this.messageService.add({severity: 'error', detail: 'General server error during login!Try latter'});
     } else {
        const user = this.store.selectSnapshot(UserState.userDetails);
        if (user == null) {
          this.messageService.add({severity: 'error', detail: 'Wrong username or password!'});
        } else {
            this.router.navigate(['/home']);
        }
      }
    });
  }

  signIn() {
    const username = this.loginForm.value.username.trim();
    const password = this.loginForm.value.password.trim();
    this.store.dispatch(new LoginAction(username, password));
  }
  displayDialog(){
    this.display = true;
  }
  sendPasswordChange(){
    // @ts-ignore
    this.loginService.startChangingPassword(this.email).subscribe(d =>{
    })
    this.display = false;
  }
}
