import { ChangeDetectionStrategy, Component, inject, Injector, Input, NgZone, Output } from '@angular/core';
import { FancyGroup } from '../fancy-row-column.model';
import { Subject } from 'rxjs';
import { FancySettings } from '../fancy-settings.model';
import { DebounceTimer } from '../../../utilities/timer-utils';
import { DropFileEvent } from '../../../shared/file-drag-drop/file-drag-drop.directive';

@Component({
  selector: 'rbj-fancy-group-menu',
  templateUrl: './fancy-group-menu.component.html',
  styleUrl: './fancy-group-menu.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FancyGroupMenuComponent<T> {
  injector = inject(Injector);
  ngZone = inject(NgZone);
  @Input() usingAltColor = false;
  deletingGroup = false;

  private clearDroppingOnGroupKeyTimer = new DebounceTimer(100, () => {
    this._droppingOnGroupKey = null;
    this.droppingOnGroupKeyChange.next(null);
  })
  @Input() groups: FancyGroup[];

  @Input() settings: FancySettings;
  private _draggingRow: boolean;
  public get draggingRow(): boolean {
    return this._draggingRow;
  }
  @Input() public set draggingRow(v: boolean) {
    if (this._draggingRow != v) {
      this._draggingRow = v;
      this.draggingRowChange.next(v);
    }
  }
  @Output() draggingRowChange = new Subject<boolean>()

  @Output() itemDropInGroup = new Subject<string>();

  private _droppingOnGroupKey: string;
  public get droppingOnGroupKey(): string {
    return this._droppingOnGroupKey;
  }
  @Input() public set droppingOnGroupKey(v: string) {
    if (this._droppingOnGroupKey != v) {
      this._droppingOnGroupKey = v;
      this.droppingOnGroupKeyChange.next(this.droppingOnGroupKey);
    }
  }
  @Input() filteringGroupKey: string;
  @Output() droppingOnGroupKeyChange = new Subject<string>();
  @Output() onFileDroppedInGroup = new Subject<FancyGroup<T>>();

  @Output() clickOnGroup = new Subject<FancyGroup<T>>();
  @Output() clickOnDeleteGroup = new Subject<FancyGroup<T>>();

  constructor() {

  }

  public onGroupListMouseUp(group: FancyGroup<T>, $event: MouseEvent) {
    if (!this.deletingGroup) {

      this.droppingOnGroupKey = group.groupKey;
      if (this.draggingRow) {
        this.itemDropInGroup.next(group.groupKey);
        //this.draggingRow = false;
      }
      setTimeout(() => {
        this.draggingRow = false;
        this.droppingOnGroupKey = null;
      }, 500);
    }
  }

  fileDroppedInGroup(group: FancyGroup<T>, event: DropFileEvent) {
    if (group) {
      group.uiFileDropList = event.files;
      this.onFileDroppedInGroup.next(group);
    }
  }
  clickGroup(group: FancyGroup<T>) {
    if (!this.deletingGroup) {
      this.clickOnGroup.next(group);
    }
  }
  removeGroup(group: FancyGroup<T>) {
    this.deletingGroup = true;
    setTimeout(() => {
      this.deletingGroup = false;
    }, 50);
    this.clickOnDeleteGroup.next(group);
  }
}
