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';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'proficiencies-table',
  templateUrl: './proficiencies-table.component.html',
  styleUrls: ['./proficiencies-table.component.scss'],
})
export class ProficienciesTableComponent {
  // public proficiencies!: any;
  public proficiencies = this.formBuilder.group({
    simple: false,
    martial: false,
    other: '',
    light: false,
    medium: false,
    heavy: false,
    shields: false,
    tools: this.formBuilder.array([]),
    languages: this.formBuilder.array([]),
  });

  public constructor(
    public dataAccessor: DataService,
    public modalAccessor: ModalService,
    private formBuilder: FormBuilder,
  ) {}

  public ngOnInit(): void {
    // this.proficiencies.setValue(this.dataAccessor.proficiencies);
    this.setProficiencies(this.dataAccessor.proficiencies);
  }

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

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

  public openModal(): void {
    this.modalAccessor.openModal(ToolsModalComponent, {
      proficiencies: JSON.parse(JSON.stringify(this.proficiencies.value)),
    });
    const resultSubscription = this.modalAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update') {
          this.setProficiencies(result.data);
          this.updateDatabase();
        } else if (result.state === 'cancel') {
          // Do nothing
        }
        resultSubscription.unsubscribe();
      },
    );
  }

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

  public setProficiencies(data: any): void {
    const { tools, languages, ...dataWithoutToolsAndLanguages } = data;
    Object.keys(dataWithoutToolsAndLanguages).forEach((key) => {
      this.proficiencies.get(key)?.setValue(dataWithoutToolsAndLanguages[key]);
    });
    this.proficiencies.setControl('tools', this.formBuilder.array(tools));
    this.proficiencies.setControl(
      'languages',
      this.formBuilder.array(languages),
    );
  }
}
