import {Component, OnInit, ViewChild} from '@angular/core';
import {ValidationService} from '../services/validation.service';
import {LoginService} from '../services/login.service';
import {Router} from '@angular/router';
import {ApiService} from '../services/api.service';


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

  username = '';  // credentials
  password = '';
  email = '';
  message = '';  // message below login fields
  passreset = false;  // to toggle between normal login and password reset form

  @ViewChild('loginForm') loginForm;


  constructor(
    private validate: ValidationService,
    private login: LoginService,
    private api: ApiService,
    private router: Router
  ) { }

  ngOnInit() {
  }

  userLogin() {
    if (this.passreset) {  // reset password
      this.api.post('/user/passreset', {name: this.username, email: this.email}, (data, err) => {
        if (err) {
          this.message = 'Could not find a valid user';
        }
        else {
          this.message = 'Password reset, check your inbox';
        }
      });
    }
    else {
      this.login.login(this.username, this.password).then(ok => {
        if (ok) {
          this.message = 'Login successful';
          if (this.login.isLevel.read) {
            this.router.navigate(['/samples']);
          }
          else {  // navigate prediction users to prediction as they cannot access samples
            this.router.navigate(['/prediction']);
          }
        }
        else {
          this.message = 'Wrong credentials!';
        }
      });
    }
  }
}
