import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { take } from 'rxjs/operators';
import { ProfileService } from '../profile.service';
import { User } from '../User';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent implements OnInit {
  private _currentUser: Observable<User>;
  public profileForm: FormGroup = new FormGroup({
    given_name: new FormControl(''),
    family_name: new FormControl(''),
    middle_name: new FormControl(''),
    nickname: new FormControl(''),
    preferred_username: new FormControl(''),
    birthdate: new FormControl(''),
    gender: new FormControl(''),
    phone_number: new FormControl(''),
    website: new FormControl(''),
    address: new FormGroup({
      street_address: new FormControl(''),
      locality: new FormControl(''),
      region: new FormControl(''),
      postal_code: new FormControl(''),
      country: new FormControl('')
    })
  });


  constructor(
    private profileService: ProfileService
  ) { }

  ngOnInit() {
    this._currentUser = this.profileService.currentUser();
    this.profileService.currentUser().pipe(take(1)).subscribe((user: User) => {
      if (user) {
        this.profileForm.patchValue(user.claims);
      }
    });
  }

  submitUpdatedUserInfo() {
    this.profileService.updateCurrentUser({claims: this.profileForm.value}).subscribe();
  }
}
