import { AfterViewInit, Component, Inject, 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: null | number = null;
  slRepUserId: null | number = null;
  slRepGroupId: null | number = null;
  slRightGroupId: null | number = null;
  slUserRepId: null | number = null;

  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;

  userGroupOnSelectedRows = (rows: GuiSelectedRow[], isUser: boolean = true) => {
    if (rows.length > 0) {
      this.users.safelyUnselectAll();

      if (isUser) {
        this.useRepLabel = `Vertretungen von ${rows[0].source?.username}`
        this.userReps.fetchData(rows[0].source?.id)
        this.slUserId = rows[0].source?.id
      }
      else {
        this.useRepLabel = `Vertretungen von ${rows[0].source?.name}`
        this.userReps.fetchData(undefined, rows[0].source?.id)
        this.slUserId = rows[0].source?.id
      }
    }
  }

  userOnSelectedRows = (rows: GuiSelectedRow[]) => {
    this.userGroupOnSelectedRows(rows, true);
  }

  groupOnSelectedRows = (rows: GuiSelectedRow[]) => {
    this.userGroupOnSelectedRows(rows, false);
  }

  repUserOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length == 0 && this.slRepUserId) {
      if (!this.slUserId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie den Benutzer!",
        });
      }
      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,
          repUserId: this.slRepUserId,
          addedWho: 'DEFAULT'
        }
        this.userRepService.create(newUserRep).subscribe({
          next: (response) => {
            this.slRepUserId = null;
            this.repUsers.safelyUnselectAll()
            if (this.slUserId != null)
              this.userReps.fetchData(this.slUserId)
          },
          error: (error) => {
            Swal.fire({
              icon: "error",
              title: "Oops...",
              text: `Dieser Vorgang ist nicht möglich.`,
            });
          }
        });
      }

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

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

      this.slRepGroupId = null;
    }
    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 = null;
          this.userReps.safelyUnselectAll();
          if (this.slUserId != null)
            this.userReps.fetchData(this.slUserId)
        },
        error: (err) => {
          this.slUserRepId = null;
          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;
    }
  }
}