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

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter, first } from 'rxjs/operators';
import { ModalWindowService } from '../../core/modal-window/modal-window.service';
import { ColumnSelectorComponent } from './column-selector.component';
import { ColumnSelectorDialogModel } from './column-selector.model';

@Injectable({
  providedIn: 'root',
})
export class ColumnSelectorService {
  private afterClosed$: BehaviorSubject<any> = new BehaviorSubject<any>(undefined);

  /**
   * Signals when column selector dialog is closed.
   */
  public afterClosed(): Observable<any> {
    // skips undefined values and unsubscribe after returning once
    // this way this method does not need to be unsubscribed
    return this.afterClosed$.asObservable().pipe(
      filter((a) => !!a),
      first()
    );
  }

  constructor(private modalWindowService: ModalWindowService) {}

  /**
   * Shows the column selector dialog using given options and returns an observable that is notified when the dialog is finished closing.
   * @param options The options to apply to the column selector dialog.
   */
  show(options: ColumnSelectorDialogModel): Observable<any> {
    // reset close
    this.afterClosed$.next(undefined);

    // show column selector dialog
    this.modalWindowService
      .openDialogWithComponent(ColumnSelectorComponent, {
        data: options,
        width: options.dialogScreenWidth || '800px',
      })
      .afterClosed()
      .subscribe((result) => {
        this.afterClosed$.next(result);
      });
    return this.afterClosed();
  }
}
