import { createSelector } from '@ngrx/store';
import { Dictionary } from '@cmf/core';
import { customersStateAdapter } from './customers.state';
import { selectCustomerState } from '../customer.selector';
import { Customer } from './defs';

export const selectCustomersState = createSelector(selectCustomerState, (s) => s.customers);

export const { selectAll, selectEntities } = customersStateAdapter.getSelectors(selectCustomersState);

export const selectCustomers = createSelector(selectEntities, (entities: Dictionary<Customer>) => entities);

export const selectCustomer = createSelector(selectEntities, (entities: Dictionary<Customer>, id: number) => entities[id]);

export const selectAddresses = createSelector(
  selectEntities,
  (entities: Dictionary<Customer>, id: number) => entities[id] && entities[id].addresses
);

export const selectGeneralAddress = createSelector(
  selectEntities,
  (entities: Dictionary<Customer>, id: number) => entities[id] && entities[id].addresses && entities[id].addresses.generalAddress
);

export const selectShippingAddresses = createSelector(
  selectEntities,
  (entities: Dictionary<Customer>, id: number) => entities[id] && entities[id].addresses.shippingAddresses
);

export const selectDefaultShippingAddress = createSelector(
  selectEntities,
  (entities: Dictionary<Customer>, id: number) =>
    entities[id] &&
    entities[id].addresses.shippingAddresses &&
    entities[id].addresses.shippingAddresses.find((address) => address.isDefault)
);

export const selectPayerAddresses = createSelector(
  selectEntities,
  (entities: Dictionary<Customer>, id: number) => entities[id] && entities[id].addresses && entities[id].addresses.payerAddresses
);

export const selectDefaultPayerAddresses = createSelector(
  selectEntities,
  (entities: Dictionary<Customer>, id: number) =>
    entities[id] && entities[id].addresses && entities[id].addresses.payerAddresses.find((address) => address.isDefault)
);
