import { Component, OnInit } from "@angular/core";
import { UserService } from "../../shared/user.service";
import { Router } from "@angular/router";
import { NgForm } from "@angular/forms";


@Component({
  selector: 'app-edit-profile',
  templateUrl: './edit-profile.component.html',
  styleUrls: ['./edit-profile.component.css']
})
export class EditProfileComponent implements OnInit {
  emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  showSucessMessage: boolean;
  serverErrorMessages: string;
  userDetails;
  nameModel : any;

  constructor(private router: Router, public userService: UserService) {}

  ngOnInit() {
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res["user"];
        this.nameModel = {fullName: this.userDetails.fullName, email: this.userDetails.email,password:''};
      },
      err => {}
    );
  }
  /**
   * This function gets called when a user submits edit profile information.
   * It will take the information taken from the form (information from the input boxes in the HTML)
   * and send it to the backend server to be sent to the MongoDB
   */
  onSubmit(form: NgForm) {
    this.userService.updateProfile(form.value).subscribe(
      res => {
        this.showSucessMessage = true;
        setTimeout(() => (this.showSucessMessage = false), 4000);
        location.reload();
      },
      err => {
        if (err.status === 422) {
          this.serverErrorMessages = err.error.join("<br/>");
        } else
          this.serverErrorMessages =
            "Something went wrong.Please contact admin.";
      }
    );
  }


  //Redirects to the profile page
  profile() {
    if (!this.userService.isLoggedIn()) {
      this.router.navigate(["/login"]);
    } else {
      this.router.navigate(["/userprofile"]);
    }
  }

  //Allows you to logout from the Click History page
  onLogout() {
    this.userService.deleteToken();
    this.router.navigate(["/login"]);
  }
}
