import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { EMPTY, throwError } from 'rxjs';
import { catchError, concatMap, tap } from 'rxjs/operators';
import { BaseForm } from 'src/app/core/base/base-form';
import { BaseFormUid } from 'src/app/core/base/base-form-uid';
import { UserOpenidService } from 'src/app/core/service/openid/user.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
    viewPass = {
        password: false,
        confirm: false
    };
  constructor(
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    public fb: FormBuilder,
    private userOpenidSV: UserOpenidService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) {
    super(router,activeRoute,fb,location)
   }

  ngOnInit(): void {
    this.canEdit = this.state == 'edit'? true : false
    if(this.state == 'edit'){
      this.userOpenidSV.get(this.id).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){
        const save$ = this.state === 'edit'? this.userOpenidSV.changePassword(uid,form) : this.userOpenidSV.add(form);
        return save$.pipe(
            tap(() => this.state === 'edit'? this.swSV.updateSuccess() : this.swSV.saveSuccess()),
            concatMap(() => {
                if(this.state === 'edit'){
                    const status$ = form.is_active === true ? this.userOpenidSV.active(uid) : this.userOpenidSV.inactive(uid);
                    return status$;
                }else{
                    return EMPTY;
                }
            }),
            tap(() => this.location.back()),
            catchError(err => {
                this.swSV.err()
                return throwError(err)
            })
        ).subscribe()
    }else{
      this.swSV.errText('รหัสผ่านไม่ตรงกัน')
    }
  }

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

    changeViewPass(type){
      if (type === 'confirm'){
          this.viewPass.confirm = !this.viewPass.confirm;
      }else {
          this.viewPass.password = !this.viewPass.password;
      }
    }

}
