import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
import { GuiRowSelection, GuiRowSelectionMode, GuiRowSelectionType, GuiSelectedRow } 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 { DirUserTableComponent } from '../tables/dir-user-table/dir-user-table.component';
import { UserService } from '../../services/api/user.service';
import { User } from '../../models/user-management.api.models'
import { RefreshService } from '../../services/button/refresh.service';

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

  initWithoutData = () => { }

  constructor(private gService: GroupService, private uService: UserService, private rService: RefreshService) {
  }

  ngOnInit(): void {
  }

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

  ngAfterViewInit(): void {
    //this.dirUsers.loading = false;
  }

  dirGroupsRowSelection: GuiRowSelection = {
    enabled: true,
    type: GuiRowSelectionType.ROW,
    mode: GuiRowSelectionMode.SINGLE
  }

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

  addSelectedUsers() {
    let requests = new Array<Observable<User | null>>();
    let numAdded: number = 0;
    for (let row of this.dirUsers.selectedRows) {
      // Create an Observable for each request and add it to the requests array
      requests.push(
        this.uService.create({
          email: row?.source?.mail?.[0],
          prename: row.source?.givenname?.[0],
          username: row.source?.samaccountname?.[0],
          name: row.source?.sn?.[0],
        }).pipe(
          catchError((err) => {
            return of(null);
          })
        )
      );
    }

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

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

  dirGroupOnSelectedRows = (rows: Array<GuiSelectedRow>) => {
    if (rows.length > 0) {
      this.dirGroups.safelyUnselectAll()
      let groupName: string = rows[rows.length - 1].source.samaccountname;
      this.dirUsers.fetchDataByGroupName(groupName);
    }
  }
}
