import { ButtonSize } from '@af/digi-ng/_button/button';
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import {
  FilterTreeNodeData,
  TreeNodeModel,
  TreeNodesSelectorService,
} from '../../services/tree-nodes-selector.service';

@Component({
  selector: 'msfa-tree-nodes-selector-panel',
  templateUrl: './tree-nodes-selector-panel.component.html',
  styleUrls: ['./tree-nodes-selector-panel.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TreeNodesSelectorPanelComponent implements OnInit {
  @Input() rootNode: TreeNodeModel | null = null;
  @Input() headingText: string;
  @Input() confirmationButtonText = 'Spara';
  @Output() selectedChangesConfirmed = new EventEmitter<TreeNodeModel>();
  @Output() closePanelRequested = new EventEmitter<void>();
  @Output() focusControlToggleBtnRequested = new EventEmitter<void>();

  readonly ButtonSize = ButtonSize;

  pendingRootNode: TreeNodeModel | null = null;
  visibleChildren: Array<TreeNodeModel> | null = null;

  constructor(private treeNodesSelectorService: TreeNodesSelectorService) {}

  ngOnInit(): void {
    this.setupPendingRootNode();
  }

  private setupPendingRootNode(): void {
    this.pendingRootNode = this.treeNodesSelectorService.getClonedTreeNode(this.rootNode);

    if (!this.pendingRootNode) {
      return;
    }

    this.pendingRootNode.isRoot = true;
    this.updateExpandedChildPanel(this.pendingRootNode);
  }

  clearSelections(): void {
    this.pendingRootNode = this.treeNodesSelectorService.getTreeNodeWithNoNodesSelected(this.pendingRootNode);
    this.updateExpandedChildPanel(this.pendingRootNode);
  }

  closePanel(): void {
    this.selectedChangesConfirmed.emit(this.pendingRootNode);
    this.closePanelRequested.emit();
  }

  closePanelAndFocusControlToggleBtn(): void {
    this.closePanel();
    this.focusControlToggleBtnRequested.emit();
  }

  hasSelectedDescendant(treeNode: TreeNodeModel): boolean {
    return this.treeNodesSelectorService.hasSelectedLeafNodeDescendant(treeNode);
  }

  updateExpandedChildPanel(treeNode: TreeNodeModel): void {
    this.visibleChildren = this.treeNodesSelectorService.getVisibleChildren(treeNode);
  }

  updateVisibleChildren(filterTreeNodeData: FilterTreeNodeData): void {
    filterTreeNodeData.treeNode.children = this.treeNodesSelectorService.getFilteredTreeNodeChildren(
      filterTreeNodeData
    );

    filterTreeNodeData.treeNode.filterText = filterTreeNodeData.text;

    this.visibleChildren = this.treeNodesSelectorService.getVisibleChildren(filterTreeNodeData.treeNode);
  }
}
