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";
import {
  PasswordStrengthValidator,
  ValidatorComponent
} from "../plugins/validator/validator.component";

@Component({
  selector: "app-profile",
  templateUrl: "./profile.component.html",
  styleUrls: ["./profile.component.scss"]
})
export class ProfileComponent implements OnInit {
  title = "Perfil del usuario";
  userForm: FormGroup;
  submitted: boolean = false;
  editProfile: boolean;

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

  ngOnInit() {
    this.userForm = this.formBuilder.group(
      {
        old_password: ["", Validators.required],
        new_password: [
          "",
          [
            Validators.required,
            Validators.minLength(8),
            PasswordStrengthValidator
          ]
        ],
        confirm_new_password: ["", Validators.required]
      },
      {
        validator: ValidatorComponent("new_password", "confirm_new_password")
      }
    );
  }

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

  editUser() {
    this.submitted = true;
    // stop here if form is invalid
    if (this.userForm.invalid) {
      return;
    }

    let user = {
      old_password: this.f.old_password.value,
      new_password: this.f.new_password.value,
      confirm_new_password: this.f.confirm_new_password.value
    };

    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
    this.userService.changePassword(user).subscribe(
      success => {
        if (success) {
          Swal.fire({
            allowOutsideClick: false,
            icon: "success",
            showCancelButton: false,
            title: "Exito",
            confirmButtonText: "Se ha actualizado su perfil exitosamente"
          }).then(result => {
            Swal.close();
            window.location.reload();
          });
        }
      },
      err => {
        Swal.fire({
          icon: "error",
          title: "Error al guardar",
          text: err.message
        });
      }
    );
  }
}
