import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, Validators, FormArray } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { BaseForm } from 'src/app/core/base/base-form';
import { OpenidService } from 'src/app/core/base/base-openid-service';
import { UserOpenidService } from 'src/app/core/service/openid/user.service';
import { AppRoleService } from 'src/app/core/service/security/app-role.service';
import { AppUserService } from 'src/app/core/service/security/app-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 BaseForm implements OnInit {
  role$ = new Observable()
  user: any = [];
  constructor(
    public router: Router,
    public fb: FormBuilder,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private appRoleSV: AppRoleService,
    private swSV: SweetalertService,
    private cdr: ChangeDetectorRef,
    private appUserSV: AppUserService,
    private userOpenidSV: UserOpenidService
  ) {
    super(router,activeRoute,fb,location)
   }

  ngOnInit(): void {
    this.userOpenidSV.getAll().pipe(tap(x => this.user = x)).subscribe()
    this.role$ = this.appRoleSV.getAll()
    if(this.state == 'edit'){
      this.appUserSV.get(this.id).pipe(
        tap(x => this.setupForm(x)),
      ).subscribe()
    }
  }

  setDisplayName(x){
    this.form.get('display_name').setValue(x.display_name)
  }

  setupForm(x){
    this.form.patchValue(x)
    this.form.setControl('app_user_roles',this.fb.array(x.app_user_roles.map(z => this.createArray(z))))
    this.cdr.detectChanges()
  }

  createForm(){
    return this.fb.group({
      app_user_id: [null],
      login_name: ['',Validators.required],
      display_name: [''],
      app_user_type_id: 1,
      app_user_roles: this.fb.array([
        this.createArray()
      ])
    })
  }

  createArray(role?){
    return this.fb.group({
      app_user_id: role?.app_user_id,
      app_role_id: [role?.app_role_id,Validators.required],
      app_user_role_id: role?.app_user_role_id
    })
  }

  add(){
    const form = this.form.get('app_user_roles') as FormArray
    form.push(this.createArray())
  }

  remove(i){
    const form = this.form.get('app_user_roles') as FormArray
    form.removeAt(i)
  }

  save(){
    const form = this.form.getRawValue()
    if(this.state == 'edit'){
      this.appUserSV.update2(form).pipe(
        tap(x => this.swSV.updateSuccess()),
        tap(x => this.location.back()),
        catchError(err => {
          this.swSV.err()
          return throwError(err)
        })
      ).subscribe()
    } else {
      this.appUserSV.add(form).pipe(
        tap(x => this.swSV.saveSuccess()),
        tap(x => this.location.back()),
        catchError(err => {
          this.swSV.err()
          return throwError(err)
        })
      ).subscribe()
    }
  }

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