import { Component } from '@angular/core';
import { PopupBaseComponent } from '@app_core/components/popup-base/popup-base.component';
import { WindreamSearchItem } from '@app_models/windream-search-item';
import { WindreamSearchItemToWindreamSearchToDepartment } from '@app_models/windream-search-item-to-windream-search-to-department';
import { DepartmentDataService } from '@app_modules/department/department-data.service';

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

  public windreamSearchItemIds: number[] = [];

  constructor(
    public departmentDataService: DepartmentDataService,
  ) {
    super();
    this.departmentDataService.windreamSearchItemList.load();
    this.getNotUsedwindreamSearchItems = this.getNotUsedwindreamSearchItems.bind(this);
  }


  public get windreamSearchItemList(): WindreamSearchItem[] {
    return this.departmentDataService.windreamSearchItemList.items;
  }

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

  getNotUsedwindreamSearchItems(dep: WindreamSearchItem) {
    return !this.list.items.find((item) => item['windreamSearchItemId'] === dep.entityId);
  }


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

}
