import { Component, ViewChild } from '@angular/core';
import { HenselSelectionComponent } from '@app_core/components/hensel-selection/hensel-selection.component';
import { PopupBaseComponent } from '@app_core/components/popup-base/popup-base.component';
import { WindreamIndex } from '@app_models/windream-index';
import { WindreamIndexToWindreamSearchToDepartment } from '@app_models/windream-index-to-windream-search-to-department';
import { DepartmentDataService } from '@app_modules/department/department-data.service';

@Component({
  selector: 'app-department-windream-index-popupedit',
  templateUrl: './department-windream-index-popupedit.component.html',
  styleUrls: ['./department-windream-index-popupedit.component.scss']
})
export class DepartmentWindreamIndexPopupeditComponent extends PopupBaseComponent  {

  public windreamIndexIds: number[] = [];
  @ViewChild('input_windreamIndex') input_windreamIndex: HenselSelectionComponent;

  constructor(
    public departmentDataService: DepartmentDataService,
  ) {
    super();
    this.departmentDataService.windreamIndexList.load();
  }


  public get windreamIndexList(): WindreamIndex[] {
    return this.departmentDataService.windreamIndexList.items;
  }

  public get focusedItem(): WindreamIndexToWindreamSearchToDepartment {
    return <WindreamIndexToWindreamSearchToDepartment>(this._focusedItem);
  }

  getNotUsedwindreamIndexes = (dep: WindreamIndex) => {
    return !this.list.items.find((item) => item['windreamIndexId'] === dep.entityId);
  }

  save = () => {
    let maxSeq = this.list.items.reduce<number>((max: number, _index: WindreamIndexToWindreamSearchToDepartment) => max > _index.seq ? max : _index.seq, 0);
    // for each selected WindreamIndexIds
    this.windreamIndexIds.forEach(windreamIndexId => {
      // create new WindreamIndexMap Item
      const newWindreamIndex = new WindreamIndexToWindreamSearchToDepartment();
      // calculate highest seq
      newWindreamIndex.seq = ++maxSeq;
      newWindreamIndex.windreamIndexId = windreamIndexId;
      newWindreamIndex.windreamSearchToDepartmentId = this.focusedItem.windreamSearchToDepartmentId;
      newWindreamIndex.entityChanged = true;
      this.list.items.push(newWindreamIndex);
    });
    this.list.save(() => {
      this.baseEntityWrapper.resetEditMode();
      this.close(true);
    });
  }

}
