import { Injectable } from '@angular/core';
import { SupplierDTO } from '@swagger/oms';
import { State, Action, StateContext, Selector } from '@ngxs/store';
import { CollectingShelfService } from '../../services/collecting-shelf.service';
import { tap } from 'rxjs/operators';
import * as actions from '../actions/suppliers.actions';

export class SupplierStateModel {
  suppliers: { [id: number]: SupplierDTO };
}

@State<SupplierStateModel>({
  name: 'suppliers',
  defaults: {
    suppliers: [],
  },
})
@Injectable()
export class SupplierState {
  constructor(private shelfService: CollectingShelfService) {}

  @Selector()
  static getSuppliers(state: SupplierStateModel) {
    return state.suppliers;
  }

  @Action(actions.LoadSuppliers)
  loadSuppliers(ctx: StateContext<SupplierStateModel>, {}: actions.LoadSuppliers) {
    return this.shelfService.getSuppliers().pipe(
      tap((_suppliers: SupplierDTO[]) => {
        const state = ctx.getState();
        const suppliers = { ...state.suppliers };

        _suppliers.forEach((supplier: SupplierDTO) => {
          suppliers[supplier.id] = supplier;
        });
        ctx.patchState({ suppliers });
      })
    );
  }
}
