import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { GuiRowSelection, GuiRowSelectionMode, GuiRowSelectionType } from '@generic-ui/ngx-grid';
import Swal from 'sweetalert2';
import { GroupService } from '../../services/api/group.service';
import { Observable, forkJoin, of } from 'rxjs';
import { catchError, finalize } from 'rxjs/operators';
import { DirGroupTableComponent } from '../tables/dir-group-table/dir-group-table.component';
import { DirGroup } from '../../models/user-management.api.models';

@Component({
  standalone: true,
  imports: [DirGroupTableComponent],
  selector: 'app-group-dir-import',
  templateUrl: './group-dir-import.component.html',
  styleUrl: './group-dir-import.component.css'
})
export class GroupDirImportComponent implements OnInit {

  initWithoutData = () => { }

  constructor(private gService: GroupService) {
  }

  ngOnInit(): void {
  }


  @ViewChild('dirGroups') dirGroups!: DirGroupTableComponent;

  dirGroupsRowSelection: GuiRowSelection = {
    enabled: true,
    type: GuiRowSelectionType.CHECKBOX,
    mode: GuiRowSelectionMode.MULTIPLE
  }

  dirUsersRowSelection: GuiRowSelection = {
    enabled: true,
    type: GuiRowSelectionType.CHECKBOX,
    mode: GuiRowSelectionMode.MULTIPLE
  }

  addSelectedGroups() {
    let requests = new Array<Observable<DirGroup | null>>();
    let numAdded: number = 0;
    for (let row of this.dirGroups.selectedRows) {
      requests.push(
        this.gService.createByDir({ samaccountname: row?.source?.samaccountname }).pipe(
          catchError((err) => {
            return of(null);
          })
        )
      );
    }

    forkJoin(requests).pipe(
      // finalize is executed after all requests are completed or when an error occurs
      finalize(() => {
        Swal.fire({
          icon: "success",
          title: "Abgeschlossen",
          text: `${numAdded} neue Gruppen hinzugefügt`,
          position: "center",
          showConfirmButton: false,
          timer: 3000
        });

        this.dirGroups.safelyUnselectAll();
      })
    ).subscribe({
      next: (results) => {
        numAdded += results.filter(result => result !== null).length;
      },
      error: (err) => {
      }
    });
  }
}
