import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { GroupTableComponent } from '../../components/tables/group-table/group-table.component';
import { UserTableComponent } from '../../components/tables/user-table/user-table.component';
import { MatTabsModule } from '@angular/material/tabs';
import { GuiCellEdit, GuiSelectedRow } from '@generic-ui/ngx-grid';
import { GroupFormComponent } from '../../components/forms/group-form/group-form.component';
import { BasePageComponent } from '../base-page/base-page.component';
import { Group } from '../../models/user-management.api.models';
import { firstValueFrom, forkJoin } from 'rxjs';
import Swal from 'sweetalert2';
import { env } from '../../../environments/environment';

@Component({
  standalone: true,
  imports: [GroupTableComponent, UserTableComponent, MatTabsModule],
  selector: 'app-group',
  templateUrl: './group.component.html',
  styleUrl: './group.component.css'
})
export class GroupComponent extends BasePageComponent implements AfterViewInit {
  initWithoutData = () => { }

  cellEditing: GuiCellEdit = {
    enabled: true,
    cellEdit: (value: any, item: Group, index: number) => {
      if (!this.updateService.isEditable || !item.internal)
        return false;

      this.updateService.setAsync("group_" + item.id!.toString(), async () => {
        await firstValueFrom(this.groupTable.service.update(item))
      })
      return true;
    }
  }

  private sGroupId = null;

  ngAfterViewInit(): void {
    this.buttonVisibilityService.setVisibleOnly(this.refreshService, this.creationService, this.updateService)
    this.refreshService.removeAll()
    this.refreshService.add(() => {
      this.groupTable.fetchData();
      if (this.sGroupId)
        this.userTable.fetchDataByGroupId(this.sGroupId);
    });
    this.creationService.component = GroupFormComponent

    this.deletionService.add(() => this.handleDeleteRequest());
  }

  @ViewChild("groupTable") groupTable!: GroupTableComponent;
  @ViewChild("userTable") userTable!: UserTableComponent;

  groupsOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length > 0) {
      this.sGroupId = rows[0].source.id;
      if (this.sGroupId)
        this.userTable.fetchDataByGroupId(this.sGroupId);
    }
  }

  handleDeleteRequest() {
    const sRows = this.groupTable.selectedRows;
    if (sRows.length > 0)
      Swal.fire({
        title: "Löschen besttigen",
        html: `<p class="text-start">Dieser Vorgang ist unwiderruflich. Möchten Sie fortfahren?<br><br>Anzahl der zu löschenden Einträge: ${sRows.length}</p>`,
        showDenyButton: true,
        confirmButtonText: "Ja",
        denyButtonText: `Nein`
      }).then((result) => {
        if (result.isConfirmed) {
          const deleteRequests = sRows.map(sRow => this.groupTable.service.delete(sRow.source.id!));
          forkJoin(deleteRequests).subscribe({
            next: () => {
              this.updateService.executeAllAsync().then(() => {
                this.refreshService.executeAll();
              })

              Swal.fire({
                text: `${sRows.length} Einträge wurden erfolgreich gelöscht.`,
                icon: "success"
              })
            },
            error: err => Swal.fire({
              title: "Fehler",
              text: `Dieser Vorgang ist nicht möglich.`,
              icon: "error"
            })
          });
        }
      });
  }

  get complete_group_cols() {
    return env.columnNames.group.complete
  }
}