import { Component } from '@angular/core';
import {
  CdkDragDrop,
  CdkDropList,
  CdkDrag,
  moveItemInArray,
} from '@angular/cdk/drag-drop';
import { DataService } from 'src/services/data/data.service';
import { DetailsService } from 'src/services/details/details.service';
import { Trait } from 'src/interfaces/interfaces';
import { TraitDetailsComponent } from './trait-details/trait-details.component';
import { ModalService } from 'src/services/modal/modal.service';
import { TraitModalComponent } from './trait-modal/trait-modal.component';
@Component({
  selector: 'trait-table',
  templateUrl: './trait-table.component.html',
  styleUrls: ['./trait-table.component.scss'],
})
export class TraitTableComponent {
  public traits!: Trait[];

  public isToUpdate: boolean = false;
  public traitToUpdate: Trait | undefined;
  public updateTraitIndex: number | undefined;

  public constructor(
    public dataAccessor: DataService,
    public modalAccessor: ModalService,
    private detailsAccesssor: DetailsService,
  ) {}

  public ngOnInit(): void {
    this.traits = this.dataAccessor.traits;
  }

  // FUNCTIONS

  public openModal(isUpdate: boolean, index?: number): void {
    this.modalAccessor.openModal(TraitModalComponent, {
      trait:
        index !== undefined
          ? JSON.parse(JSON.stringify(this.traits[index]))
          : undefined,
      isUpdate: isUpdate,
    });
    const resultSubscription = this.modalAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update') {
          this.updateTrait(result.data, index!);
        } else if (result.state === 'add') {
          this.addTrait(result.data);
        }
        resultSubscription.unsubscribe();
      },
    );
  }

  // add
  public addTrait(trait: Trait): void {
    this.traits.push(trait);
    this.updateDatabase();
  }

  //  update
  public updateTrait(ability: Trait, index: number): void {
    this.traits[index] = ability;
    this.updateDatabase();
  }

  // delete
  private deleteTrait(index: number): void {
    this.traits.splice(index, 1);
    this.updateDatabase();
  }

  public updateDatabase(): void {
    this.dataAccessor.traits = this.traits;
  }

  // details Panel

  public openDetailsPanel(index: number): void {
    this.detailsAccesssor.openPanel(TraitDetailsComponent, {
      trait: this.traits[index],
    });
    const resultSubscription = this.detailsAccesssor.result$.subscribe(
      (result) => {
        if (result.state === 'delete') {
          this.deleteTrait(index);
        } else if (result.state === 'update') {
          this.openModal(true, index);
        }
        resultSubscription.unsubscribe();
      },
    );
  }

  // UTILITY

  public drop(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this.traits, event.previousIndex, event.currentIndex);
    this.updateDatabase();
  }
}
