import { Component, OnInit } from "@angular/core";
import { FormGroup, FormBuilder, Validators, FormArray } 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;
  isLoadingOrganization: boolean;
  listOrganization: any;
  selectedHobbiesNames: [string];

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

  get organizationsFormArr(): FormArray {
    return this.f && <FormArray>this.f.organizationsFormArr;
  }

  get organizationsFormGroup(): FormGroup {
    return this.f && <FormGroup>this.f.organizationsFormGroup;
  }

  get organizationsFormGroupSelectedIds(): string[] {
    let ids: string[] = [];
    for (var key in this.organizationsFormGroup.controls) {
      if (this.organizationsFormGroup.controls[key].value) {
        ids.push(key);
      } else {
        ids = ids.filter(id => id !== key);
      }
    }
    return ids;
  }

  ngOnInit() {
    this.isLoadingOrganization = true;
    this.userForm = this.formBuilder.group({
      first_name: [""],
      last_name: [""],
      email: [""],
      role: [""]
    });
  }

  buildOrganizationFormGroup(
    organizations: any,
    selectedOrganizationIds: string[] = []
  ): FormGroup {
    let group = this.formBuilder.group({});
    organizations.forEach(category => {
      let isSelected = selectedOrganizationIds.some(id => id === category.id);
      group.addControl(category.id, this.formBuilder.control(isSelected));
    });
    return group;
  }

  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({}).then(result => {
            if (result.value) {
              window.location.href = "#/users";
            }
          });
        }
      });
  }
}
