import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { GuiColumn, GuiSelectedRow } from '@generic-ui/ngx-grid/gui/grid/src/core/api/gui.grid.public-api';
import { UserTableComponent } from '../../components/tables/user-table/user-table.component';
import { UserRepTableComponent } from '../../components/tables/user-rep-table/user-rep-table.component';
import { GroupTableComponent } from '../../components/tables/group-table/group-table.component';
import { UserRepService } from '../../services/api/user-representation.service';
import Swal from 'sweetalert2';
import { MatTabsModule, MatTabGroup } from '@angular/material/tabs';
import { env } from '../../../environments/environment';
import { BasePageComponent } from '../base-page/base-page.component';
import { UserRep } from '../../models/user-management.api.models';

@Component({
  standalone: true,
  imports: [MatTabsModule, MatTabGroup, UserTableComponent, GroupTableComponent, UserRepTableComponent],
  selector: 'app-user-representation',
  templateUrl: './user-representation.component.html',
  styleUrl: './user-representation.component.css'
})
export class UserRepresentationComponent extends BasePageComponent implements AfterViewInit {

  useRepLabel: string = "";
  groupColumns: Array<GuiColumn>;
  groupRepCols: Array<GuiColumn>;
  slUserId?: number;
  slGroupId?: number;
  slRepUserId?: number;
  slRepGroupId?: number;
  slUserRepId?: number;

  initWithoutData = () => { }

  constructor(private userRepService: UserRepService) {
    super()
    this.groupRepCols = env.columnNames.group.representative;
    this.groupColumns = env.columnNames.group.right;
    this.userRepService = userRepService;
  }

  ngAfterViewInit(): void {
    this.buttonVisibilityService.setVisibleOnly(this.refreshService, this.transferService)
    this.refreshService.removeAll();
    this.refreshService.add(() => {
      this.users.fetchData();
      this.repUsers.fetchData();
      this.repGroups.fetchData();
      this.groups.fetchData();
    })
    this.transferService.add(() => {
      this.repUsers.safelyUnselectAll();
      this.repGroups.safelyUnselectAll();
      this.userReps.safelyUnselectAll();
    })
  }

  @ViewChild("users") users!: UserTableComponent;
  @ViewChild("groups") groups!: GroupTableComponent;
  @ViewChild("repUsers") repUsers!: UserTableComponent;
  @ViewChild("repGroups") repGroups!: GroupTableComponent;
  @ViewChild("userReps") userReps!: UserRepTableComponent;

  userOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length > 0) {
      this.useRepLabel = `Vertretungen von ${rows[0].source?.username}`
      this.users.safelyUnselectAll();
      this.userReps.fetchByUser(rows[0].source?.id);
      this.slGroupId = undefined;
      this.slUserId = rows[0].source?.id
    }
  }

  groupOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length > 0) {
      this.useRepLabel = `Vertretungen von ${rows[0].source?.name}`
      this.groups.safelyUnselectAll();
      this.userReps.fetchByGroup(rows[0].source?.id);
      this.slUserId = undefined;
      this.slGroupId = rows[0].source?.id
    }
  }

  repUserOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length == 0 && this.slRepUserId) {
      if (!this.slUserId && !this.slGroupId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie den Benutzer oder die Gruppe!",
        });
      }
      else if (!this.slRepUserId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie die Vertretungen Benutzer!",
        });
      }
      else {
        var newUserRep: UserRep = {
          userId: this.slUserId,
          groupId: this.slGroupId,
          repUserId: this.slRepUserId,
          addedWho: 'DEFAULT'
        }
        this.userRepService.create(newUserRep).subscribe({
          next: (response) => {
            this.slRepUserId = undefined;

            this.repUsers.safelyUnselectAll()
            this.repGroups.safelyUnselectAll()
            if (this.slUserId != undefined)
              this.userReps.fetchData(this.slUserId)
            if (this.slGroupId != undefined)
              this.userReps.fetchData(this.slGroupId)
          },
          error: (error) => {
            Swal.fire({
              icon: "error",
              title: "Oops...",
              text: `Dieser Vorgang ist nicht möglich.`,
            });
          }
        });
      }

      this.slRepUserId = undefined;
    }
    else if (rows.length > 0) {
      this.slRepUserId = rows[0].source?.id;
    }
  }

  repGroupOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length == 0 && this.slRepGroupId) {
      if (!this.slUserId && !this.slGroupId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie den Benutzer oder die Gruppe!",
        });
      }
      else if (!this.slRepGroupId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie die Vertretungen Gruppe!",
        });
      }
      else {
        var newUserRep = {
          userId: this.slUserId,
          groupId: this.slGroupId,
          repGroupId: this.slRepGroupId,
          addedWho: 'DEFAULT'
        }
        this.userRepService.create(newUserRep).subscribe({
          next: (res) => {
            this.slRepGroupId = undefined;
            this.repUsers.safelyUnselectAll()
            this.groups.safelyUnselectAll()
            if (this.slUserId != undefined)
              this.userReps.fetchData(this.slUserId)
            if (this.slGroupId != undefined)
              this.userReps.fetchData(undefined, this.slGroupId)
          },
          error: (error) => {
            Swal.fire({
              icon: "error",
              title: "Oops...",
              text: `Dieser Vorgang ist nicht möglich.`,
            });
          }
        });
      }

      this.slRepGroupId = undefined;
    }
    else if (rows.length > 0) {
      this.slRepGroupId = rows[0].source?.id;
    }
  }

  userRepOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length == 0 && this.slUserRepId) {
      this.userRepService.delete(this.slUserRepId).subscribe({
        next: (res) => {
          this.slUserRepId = undefined;
          this.userReps.safelyUnselectAll();
          if (this.slUserId != undefined)
            this.userReps.fetchData(this.slUserId)
          if (this.slGroupId != undefined)
            this.userReps.fetchData(undefined, this.slGroupId)
        },
        error: (err) => {
          this.slUserRepId = undefined;
          this.repUsers.safelyUnselectAll()
          Swal.fire({
            icon: "error",
            title: "Oops...",
            text: `Dieser Vorgang ist nicht möglich.`,
          });
        }
      })
    }
    else if (rows.length > 0) {
      this.slUserRepId = rows[0].source?.id;
    }
  }
}
