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

import { ChangeDetectorRef, Component, Inject, OnDestroy, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { BciColumnSelectorIntl } from './column-selector-intl';
import { ColumnSelectorDialogModel, ColumnSelectorItem } from './column-selector.model';

@Component({
  selector: 'bci-column-selector',
  templateUrl: './column-selector.component.html',
  styleUrls: ['./column-selector.component.scss'],
})
export class ColumnSelectorComponent implements OnInit, OnDestroy {
  changed = false;
  availableColumns: ColumnSelectorItem[];
  selectedColumns: ColumnSelectorItem[];

  /** a list of user available column */
  private userAvailableColumns: ColumnSelectorItem[];

  /** a list of user selected column */
  private userSelectedColumns: ColumnSelectorItem[];

  /** Used for component-wide unsubscription on destroy. */
  private ngUnsubscribe = new Subject<void>();

  constructor(
    @Inject(MAT_DIALOG_DATA) private data: ColumnSelectorDialogModel,
    private dialogRef: MatDialogRef<ColumnSelectorComponent>,
    public columnSelectorIntl: BciColumnSelectorIntl,
    private changeDetector: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.availableColumns = this.data.columns.filter((col) => col.visible === false);
    this.selectedColumns = this.data.columns.filter((col) => col.visible === true);

    this.columnSelectorIntl.changes
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe(() => this.changeDetector.detectChanges());
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  /**
   * Update selected labels when picklist target is changed
   */
  onSourceChanged(columns: ColumnSelectorItem[]) {
    this.changed = true;
    this.userAvailableColumns = columns;
  }

  /**
   * Update selected labels when picklist target is changed
   */
  onTargetChanged(columns: ColumnSelectorItem[]) {
    this.changed = true;
    this.userSelectedColumns = columns;
  }

  /**
   * Confirm the selected columns. Closes dialog with columns as dialog result
   */
  confirm() {
    // updates columns visibility
    this.userAvailableColumns.forEach((col) => (col.visible = false));
    this.userSelectedColumns.forEach((col) => (col.visible = true));

    // close dialog and attach updated columns
    this.dialogRef.close([...this.userAvailableColumns, ...this.userSelectedColumns]);
  }

  /**
   * Cancel changes. Closes dialog with original columns as dialog result.
   */
  cancel() {
    this.dialogRef.close(this.data.columns);
  }
}
