import { Component, OnInit } from '@angular/core';
import { ApiService } from 'app/api.service';
import { Router } from '@angular/router';
import { Title } from '@angular/platform-browser';

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

  loading: boolean = false;
  showerror: boolean = false;
  errormsg: string = '';
  data: any = {rut: '', password: ''}
  
  constructor(private api: ApiService, private router: Router, private titleService: Title) {

    this.titleService.setTitle( "GreenApp ERP - Login" );

    let myToken = localStorage.getItem("GreenappToken");
    if (myToken) {
      this.router.navigate(['/dashboard']);      
    }
  }

  ngOnInit() {

  }

  ngAfterViewInit() {
    
  }
  hideError() {
    this.showerror = false;
    this.errormsg = '';
  }

  login() {
    this.loading = true;
    this.showerror = false;
    this.errormsg = '';
    this.api.login(this.data.rut, this.data.password).subscribe((data:any) => {
      this.loading = false;
      if (data.res == "OK") {
        this.showerror = false;
        localStorage.setItem("GreenappToken", data.token);
        this.router.navigate(['/dashboard']);
      }
      else {
        this.showerror = true;
        this.errormsg = data.msg;
      }
    }, (err) => {
      this.loading = false;
      this.showerror = true;
      this.errormsg = 'Error al conectar al servidor';
    });
  }

}
