import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { BaseFormUid } from 'src/app/core/base/base-form-uid';
import { OidcAuthService } from 'src/app/core/service/oidc/oidc.service';
import { UserOpenidService } from 'src/app/core/service/openid/user.service';
import { AppTokenService } from 'src/app/core/service/security/app-token.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormComponent extends BaseFormUid implements OnInit {
  confirm;
  canEdit: boolean
  constructor(
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    public fb: FormBuilder,
    private userOpenidSV: UserOpenidService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService,
    private appTokenSV: AppTokenService,
    private oidc: OidcAuthService,
  ) {
    super(router,activeRoute,fb,location)
   }

  ngOnInit(): void {
    this.canEdit = true
    const data = this.appTokenSV.user
    this.userOpenidSV.get(data.user_uid).pipe(
      tap(x => this.setupForm(x)),
      tap(x => this.cdr.detectChanges()),
    ).subscribe()

  }

  setupForm(x){
    this.form.patchValue(x)
    this.form.get('password').setValue(null)
  }

  createForm(){
    return this.fb.group({
      user_uid: null,
      login_name: [null,Validators.required],
      display_name: [null,Validators.required],
      password: [null,[
        Validators.required,
        Validators.pattern('((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,30})')
      ]],
      confirm: [null,[
        Validators.required,
        Validators.pattern('((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,30})')
      ]],
      agency_uid: "00000000-0000-0000-0000-000000000000",
      image_url: "",
      is_active: true,
      group_name: "",
      agency_name: ""
    })
  }

  save(){
    const form = this.form.getRawValue()
    const uid = form.user_uid
    if(form.password == form.confirm){
      this.userOpenidSV.changePassword(uid,form).pipe(
        tap(x => this.swSV.updateSuccess()),
        tap(x => this.location.back()),
        tap(x => this.oidc.logout()),
        catchError(err => {
          this.swSV.err()
          return throwError(err)
        })
      ).subscribe()
    }else{
      this.swSV.errText('รหัสผ่านไม่ตรงกัน')
    }
  }

  cancel(){
    this.location.back()
  }

}
