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;

  @ViewChild('loginForm') loginForm;


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

  ngOnInit() {
  }

  login() {
    if (this.passreset) {
      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.loginService.login(this.username, this.password).then(ok => {
        if (ok) {
          this.message = 'Login successful';
          this.router.navigate(['/samples']);
        }
        else {
          this.message = 'Wrong credentials!';
        }
      });
    }
  }
}
