import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormArray, FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { BaseForm } from 'src/app/core/base/base-form';
import { BaseFormUid } from 'src/app/core/base/base-form-uid';
import { AppObjectService } from 'src/app/core/service/security/app-object.service';
import { AppPermissionService } from 'src/app/core/service/security/app-permission.service';
import { AppRoleService } from 'src/app/core/service/security/app-role.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { makeRandom } from 'src/app/shared/util/func';

@Component({
  selector: 'app-set-role-form',
  templateUrl: './set-role-form.component.html',
  styleUrls: ['./set-role-form.component.scss'],
  // changeDetection: ChangeDetectionStrategy.OnPush
})
export class SetRoleFormComponent extends BaseForm implements OnInit {
  object$ = new Observable()
  perm$ = new Observable()
  object:any = [];
  currentObject;
  perm;
  role;
  currentRole;
  constructor(
    public router: Router,
    public fb: FormBuilder,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private appRoleSV: AppRoleService,
    private appPermSV: AppPermissionService,
    private appObjectSV: AppObjectService,
    private swSV: SweetalertService,
    private cdr: ChangeDetectorRef
  ) {
    super(router,activeRoute,fb,location)
   }

  ngOnInit(): void {
    this.appObjectSV.getAll().pipe(
        map((res: any) => res.filter(object => object.status_id == 1)),
        tap(x => this.object = x)
    ).subscribe()
    this.appPermSV.getAll().pipe(tap(x => this.perm = x)).subscribe()
    this.appRoleSV.getAll().pipe(tap(x => this.role = x)).subscribe()
    if(this.state == 'edit'){
      this.appRoleSV.get(this.id).pipe(
        tap(x => this.setupForm(x))
      ).subscribe()
    }
    this.cdr.detectChanges()
  }

  setCurrentObject(x){
    this.currentObject = x
  }

  addObject(){
    const form = this.form.get('app_securities') as FormArray
    form.push(this.createDataSearchPerm(this.currentObject))
  }

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

  createForm(){
    return this.fb.group({
      app_role_id: [null],
      app_role_code: [makeRandom()],
      app_role_name_en: ['',Validators.required],
      app_role_name_th: [''],
      app_role_type_id: [null],
      status_id: [1],
      create_by: [null],
      create_datetime: [null],
      last_update_by: [null],
      last_update_datetime: [null],
      app_securities: this.fb.array([
        // this.createArray()
      ])
    })
  }

  createArray(role?){
    return this.fb.group({
      app_security_id: role?.app_security_id,
      app_role_id: role?.app_role_id,
      app_object_code: role?.app_object_code,
      app_object_id: [role?.app_object_id,Validators.required],
      app_permission_id: [role?.app_permission_id,Validators.required],
      app_permission_code: role?.app_permission_code,
      restrict_user: [role?.restrict_user || true]
    })
  }

  createFullPerm(role){
    return this.fb.group({
      app_security_id: role?.app_security_id,
      app_role_id: role?.app_role_id,
      app_object_code: role?.app_object_code,
      app_object_id: [role?.app_object_id,Validators.required],
      app_permission_id: 4,
      app_permission_code: role?.app_permission_code,
      restrict_user: [role?.restrict_user || true]
    })
  }

  createDataSearchPerm(role){
    return this.fb.group({
      app_security_id: role?.app_security_id,
      app_role_id: role?.app_role_id,
      app_object_code: role?.app_object_code,
      app_object_id: [role?.app_object_id,Validators.required],
      app_permission_id: [role?.app_permission_id,Validators.required],
      app_permission_code: role?.app_permission_code,
      restrict_user: [role?.restrict_user || true]
    })
  }

  addAllPerm(event){
    const form = this.form.get('app_securities') as FormArray
    if(event){
      this.form.setControl('app_securities',this.fb.array(this.object.map(x => this.createFullPerm(x))))
    } else {
      form.clear()
      form.push(this.createArray())
    }

  }

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

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

  save(){
    const form = this.form.getRawValue()
    form.app_role_name_th = form.app_role_name_en
    const isDuplicate = this.role.find(x => x.app_role_code == form.app_role_code)? true : false
    const current = form.app_role_code == this.currentRole?.app_role_code? true : false
    if(this.state == 'edit' && (isDuplicate == false || current == true)){
      this.appRoleSV.update2(form).pipe(
        tap(x => this.swSV.updateSuccess()),
        tap(x => this.location.back()),
        catchError(err => {
          this.swSV.err()
          return throwError(err)
        })
      ).subscribe()
    } else if (this.state == 'add' && (isDuplicate == false || current == true)){
      this.appRoleSV.add(form).pipe(
        tap(x => this.swSV.saveSuccess()),
        tap(x => this.location.back()),
        catchError(err => {
          this.swSV.err()
          return throwError(err)
        })
      ).subscribe()
    } else {
      this.swSV.errText('รหัสซ้ำกัน')
    }
  }

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