import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { DataService } from 'src/services/data/data.service';
import { ModalService } from 'src/services/modal/modal.service';
import { ToolsModalComponent } from './tools-modal/tools-modal.component';

@Component({
  selector: 'proficiencies-table',
  templateUrl: './proficiencies-table.component.html',
  styleUrls: ['./proficiencies-table.component.scss'],
})
export class ProficienciesTableComponent {
  public proficiencies!: any;

  public constructor(
    public dataAccessor: DataService,
    public modalAccessor: ModalService
  ) {
    // this.proficiencies = this.dataAccessor.proficiencies;
  }
  public ngOnInit(): void {
    this.proficiencies = this.dataAccessor.proficiencies;
  }

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

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

  public toggleAcordion(event: any): void {
    if (event.target.classList.contains('accordion')) {
      event.target.classList.toggle('active');
      var panel = event.target.nextElementSibling;
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
      } else {
        panel.style.maxHeight = '100svh'; //Hier ansetzen um es später scrollable zu machen
      }
    }
  }

  public openModal(): void {
    this.modalAccessor.openModal(ToolsModalComponent, {
      proficiencies: JSON.parse(JSON.stringify(this.proficiencies)),
    });
    const resultSubscription = this.modalAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update') {
          this.updateProficiencies(result.data);
        } else {
          throw new Error('DND-Error: Invalid result state');
        }
        resultSubscription.unsubscribe();
      }
    );
  }

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

  public updateProficiencies(data: any): void {
    this.proficiencies = data;
    this.updateDatabase();
  }
}
