import { Component, OnInit } from '@angular/core';
import { User } from '../_models';
import { FormGroup, Validators, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import {AlertService, UserService} from '../_services';
import {BaseComponent} from '../base/base.component';

@Component({
  selector: 'app-new-user',
  templateUrl: './new-user.component.html',
  styleUrls: ['./new-user.component.css']
})
export class NewUserComponent extends BaseComponent implements OnInit {

  private newUser: User;
  public userForm: FormGroup;
  public userRole: any;
  imgValue: any;

  constructor(private router: Router, private userService: UserService, private alertService: AlertService) {
    super();
  }

  ngOnInit() {
    this.createForm();
  }

  onSubmit(e: any) {
    if(this.userForm.valid){
      this.newUser = new User;
      this.newUser = this.userForm.value;
      this.alertService.clear();
      this.userService.create(this.newUser).subscribe((user: any) => {
        if(user.email){
          this.newUser = user;
          this.alertService.success("Usuario creado correctamente.", true);
          this.router.navigateByUrl('/admin/users');
        }else if (user.errors.email) {
          this.alertService.error(user.errors.email[0], false);
        }else if (user.errors.password) {
          this.alertService.error(user.errors.password[0], false);
        }
      },
      error => {
        this.alertService.error("Error creando el usuario.");
      });
    }else{
        this.alertService.error("Completa todos los campos.",false);
    }

    return false;
  }

  onCancel() {
    if (confirm('¿Estás seguro de descartar la creación del usaurio?')) {
      this.router.navigateByUrl('/admin/users');
    }
  }

  setTemporalRole(event: any){
    this.userRole = event.target.value;
  }

  createForm() {
    this.userForm = new FormGroup({
      name: new FormControl('', {
        validators: Validators.required,
        updateOn: 'blur'
      }),
      email: new FormControl('', {
        validators: [Validators.required, Validators.email],
        updateOn: 'blur'
      }),
      password: new FormControl('', {
        validators: Validators.required,
        updateOn: 'blur'
      }),
      role: new FormControl('', {
        validators: Validators.required,
        updateOn: 'change'
      }),
      branch: new FormControl(),
      branch_address: new FormControl()      
    });
  }
}

