import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { UserService } from '@app/services/user.service';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-new-user',
  templateUrl: './new-user.component.html',
  styleUrls: ['./new-user.component.scss']
})
export class NewUserComponent implements OnInit {
  title:string = "Nuevo usuario"; 
  userForm: FormGroup;
  submitted: boolean= false;


  constructor(private userService: UserService, private formBuilder: FormBuilder) {
  }

  ngOnInit() {


    this.userForm = this.formBuilder.group({
      first_name: ['', Validators.required],
      last_name: ['', Validators.required],
      email: ['', Validators.required],
      role: ['', Validators.required],
    });
  }

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

  createUser() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.userForm.invalid) {
      return;
    }
    
      this.userService.createUser(
        {
          first_name: this.f.first_name.value,
          last_name: this.f.last_name.value,
          email: this.f.email.value,
          role: +this.f.role.value,
        }
      )
      .subscribe(success => {
        if (success) {
          Swal.fire({
            allowOutsideClick: false,
            type: 'success',
            showCancelButton: false,
            title: 'Exito',
            confirmButtonText: 'El usuario ha sido creado'
          }).then((result) => {
            if (result.value) {
              window.location.href="#/users";
            }
          });
        }
        
      });
  }


}
