import { GoodsIn } from '../../models/goods-in.model';
import { State, Store, Action, StateContext } from '@ngxs/store';
import * as actions from '../actions/goods-in.actions';
import { UserStateSyncData } from '../../models/user-state-sync.model';
import { AppUserDataSync } from '../actions/app.actions';
import { Injectable } from '@angular/core';

export class GoodsInStateModel {
  goodsIn: GoodsIn;
}

@State<GoodsInStateModel>({
  name: 'goodsin',
  defaults: {
    goodsIn: {},
  },
})
@Injectable()
export class GoodsInState {
  constructor(private store: Store) {}

  @Action(actions.ReloadGoodsIn)
  reload(ctx: StateContext<GoodsInStateModel>, { goodsIn }: actions.ReloadGoodsIn) {
    ctx.patchState({ goodsIn });
  }

  @Action(actions.SetGoodsInOrders)
  setGoodsInOrders(ctx: StateContext<GoodsInStateModel>, { orders }: actions.SetGoodsInOrders) {
    const state = ctx.getState();
    const currentOrders = state.goodsIn && state.goodsIn.orders ? state.goodsIn.orders : [];
    const updatedOrders = [...currentOrders];
    if (!orders) {
      return;
    }
    orders.forEach((order) => {
      const orderIsAlreadyAdded = updatedOrders.includes(order);
      if (!orderIsAlreadyAdded) {
        updatedOrders.push(order);
      }
    });
    const goodsIn = { ...state.goodsIn, orders: updatedOrders };
    ctx.patchState({ goodsIn });
    this.syncApiState(goodsIn);
  }

  @Action(actions.SetGoodsInCachedOrders)
  setGoodsInCachedOrders(ctx: StateContext<GoodsInStateModel>, { orders }: actions.SetGoodsInCachedOrders) {
    const state = ctx.getState();
    if (!orders) {
      return;
    }
    const goodsIn = { ...state.goodsIn, cachedOrders: orders };
    ctx.patchState({ goodsIn });
    this.syncApiState(goodsIn);
  }

  @Action(actions.ClearGoodsInCachedOrders)
  clearGoodsInCachedOrders(ctx: StateContext<GoodsInStateModel>) {
    const state = ctx.getState();
    const goodsIn = { ...state.goodsIn, cachedOrders: undefined };
    ctx.patchState({ goodsIn });
    this.syncApiState(goodsIn);
  }

  @Action(actions.SetGoodsInSearch)
  setGoodsInSearch(ctx: StateContext<GoodsInStateModel>, { search }: actions.SetGoodsInSearch) {
    const state = ctx.getState();
    const goodsIn = { ...state.goodsIn, currentSearch: search };
    ctx.patchState({ goodsIn });
    this.syncApiState(goodsIn);
  }

  @Action(actions.SetGoodsInUseCache)
  setGoodsInUseCache(ctx: StateContext<GoodsInStateModel>, { useCache }: actions.SetGoodsInUseCache) {
    const state = ctx.getState();
    const goodsIn = { ...state.goodsIn, useCache: useCache };
    ctx.patchState({ goodsIn });
    this.syncApiState(goodsIn);
  }

  private syncApiState(goodsIn: GoodsIn) {
    const userSyncData: UserStateSyncData = {
      goodsIn,
    };
    const userData = JSON.stringify(userSyncData);
    this.store.dispatch(new AppUserDataSync(userData));
  }
}
