/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Component, EventEmitter, Inject, InjectionToken, OnDestroy, Output } from '@angular/core';
import { Subscription } from 'rxjs';
import { ModalWindowService } from '../../../core/modal-window/modal-window.service';
import { CommandbarButtonComponent } from '../button/commandbar-button.component';
import { CommandbarInlinefilterComponent } from '../inlinefilter/commandbar-inlinefilter.component';
import { CommandbarOptionsmenuConfig } from './commandbar-optionsmenu.model';
import { OptionsmenuDialogComponent } from './optionsmenu-dialog/optionsmenu-dialog.component';

export const COMMANDBAR_OPTIONSMENU_DATA = new InjectionToken<CommandbarOptionsmenuConfig>(
  'COMMANDBAR_OPTIONSMENU_DATA'
);

@Component({
  selector: 'bci-commandbar-optionsmenu',
  templateUrl: './commandbar-optionsmenu.component.html',
  styleUrls: ['./commandbar-optionsmenu.component.scss'],
})
export class CommandbarOptionsmenuComponent implements OnDestroy {
  @Output() closeOptionsMenu: EventEmitter<string> = new EventEmitter<string>();
  private actionsClickSubscriptions$: Subscription[];

  constructor(
    @Inject(COMMANDBAR_OPTIONSMENU_DATA) public data: CommandbarOptionsmenuConfig,
    private modalWindowService: ModalWindowService
  ) {
    this.actionsClickSubscriptions$ = [];
    if (data.actions) {
      data.actions.forEach((item) => {
        item.renderLargeVariant = true;
        if (item instanceof CommandbarButtonComponent) {
          this.actionsClickSubscriptions$.push(
            item.click.subscribe(() => this.closeOptionsMenu.emit('action clicked subscriber'))
          );
        }
      });
    }
  }

  openInlineFilter(item: CommandbarInlinefilterComponent) {
    this.modalWindowService.openDialogWithComponent(OptionsmenuDialogComponent, {
      autoFocus: false,
      data: item,
      maxWidth: 'none'
    });
  }

  actionClicked() {
    this.closeOptionsMenu.emit('action clicked directly');
  }

  ngOnDestroy(): void {
    this.actionsClickSubscriptions$.forEach((subscription) => subscription.unsubscribe());
  }
}
