import { Component, OnInit } from "@angular/core";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { Router } from "@angular/router";
import { AuthService } from "@app/services/auth2.service";
import Swal from "sweetalert2";

@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.scss"]
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  submitted: boolean = false;

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

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

  get f() {
    return this.loginForm.controls;
  }

  login() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.loginForm.invalid) {
      return;
    }

    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();

    this.authService
      .login({
        username: this.f.username.value,
        password: this.f.password.value
      })
      .subscribe(
        success => {
          if (success) {
            window.location.href = "#/dashboard";
          } else {
            Swal.fire({
              icon: "warning",
              title: "No se pudo auntenticar",
              text: "Email o contraseña incorrecta"
            });
          }
        },
        err => {
          Swal.fire({
            icon: "error",
            title: "Error al autenticar",
            text: err.message
          });
        }
      );
  }
}
