import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
  ValidationErrors,
  ValidatorFn
} from '@angular/forms';
import { Subject } from 'rxjs';
import { take } from 'rxjs/operators';
import { takeUntil } from 'rxjs/internal/operators';

import { fuseAnimations } from 'src/@fuse/animations';
import { User } from 'src/modules/user/model/user.model';
import { UserService } from 'src/modules/user/service/user.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.scss'],
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations
})
export class UserDetailComponent implements OnInit, OnDestroy {
  user: User;
  userForm: FormGroup;

  // Private
  private _unsubscribeAll: Subject<any>;

  /**
   * Constructor
   *
   * @param {EcommerceOrderService} userService
   * @param {FormBuilder} _formBuilder
   */
  constructor(
    private userService: UserService,
    private activatedRoute: ActivatedRoute,
    private formBuilder: FormBuilder
  ) {
    // Set the defaults
    // Set the private defaults
    this._unsubscribeAll = new Subject();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    // Subscribe to update order on changes
    this.activatedRoute.data.subscribe(data => {
      this.user = data.user;

      this.initializeForm();
    });
    this.userForm
      .get('password')
      .valueChanges.pipe(takeUntil(this._unsubscribeAll))
      .subscribe(() => {
        this.userForm.get('passwordConfirm').updateValueAndValidity();
      });
  }

  /**
   * On destroy
   */
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next();
    this._unsubscribeAll.complete();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Private methods
  // -----------------------------------------------------------------------------------------------------
  initializeForm(): void {
    this.userForm = this.formBuilder.group({
      username: [
        {
          value: this.user.username,
          disabled: true
        }
      ],
      password: '',
      passwordConfirm: ['', confirmPasswordValidator],
      email: this.user.email,
      nickname: [this.user.nickname, Validators.required],
      phone: this.user.phone,
      descriptions: this.user.descriptions
    });
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methodsAbstractControl
  // -----------------------------------------------------------------------------------------------------

  updateUser(): void {
    let updateUser: User = <User>this.userForm.value;
    const pw: string = this.userForm.get('password').value;
    this.userService
      .updateUser(this.user.id, updateUser, pw)
      .pipe(take(1))
      .subscribe(
        res => {
          console.log(res);
        },
        err => {
          console.log(err);
        }
      );
  }
  /**
   * Update status
   */
  updateStatus(): void {
    // const newStatusId = Number.parseInt(this.statusForm.get('newStatus').value);
    // if (!newStatusId) {
    //   return;
    // }
    // const newStatus = this.orderStatuses.find(status => {
    //   return status.id === newStatusId;
    // });
    // newStatus['date'] = new Date().toString();
    // this.order.status.unshift(newStatus);
  }
}

export const confirmPasswordValidator: ValidatorFn = (
  control: AbstractControl
): ValidationErrors | null => {
  if (!control.parent || !control) {
    return null;
  }

  const password = control.parent.get('password');
  const passwordConfirm = control.parent.get('passwordConfirm');

  if (!password || !passwordConfirm) {
    return null;
  }

  if (passwordConfirm.value === '') {
    return null;
  }

  if (password.value === passwordConfirm.value) {
    return null;
  }

  return { passwordsNotMatching: true };
};
