import { ActivatedRoute, Params } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators, FormControl } from '@angular/forms';
import { User } from '../_models/user';
import { AlertService } from '../_services/';
import { UserService } from '../_services/user.service';
import { environment } from '../../environments/environment';
import { Router } from '@angular/router';

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

  public userForm: FormGroup;
	userId: number;
  actualUser: User;
  public mypass: string = '';

	constructor(private router: Router, private userService: UserService, private route: ActivatedRoute, private alertService: AlertService) {}

	ngOnInit() {
		this.userId = this.route.snapshot.params['id'];
		this.getUser();
    this.editForm();
  }

	getUser(){
		this.userService.getById(this.userId).subscribe((user: any) => { this.actualUser = user; });
	} 

  onSubmit(event: any){
    this.userService.updateUser(this.actualUser, this.mypass).subscribe((res: any) => { 
      if(res.status){
        this.alertService.success("Usuario editado correctamente.", true);
        this.router.navigateByUrl('/admin/users');
      }else{
        this.alertService.error("Error al editar el usuario", false);
      }
    });
  }

  editForm() {
    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(),
      role: new FormControl('', {
        validators: Validators.required,
        updateOn: 'change'
      }),
      branch: new FormControl(),
      branch_address: new FormControl()      
    });
  }


}
