import { Selector } from '@ngxs/store';
import { CustomerStateModel, CustomerState } from '../state/customer.state';
import { ProcessState, ProcessStateModel } from '../state/process.state';
import { AppState, AppStateModel } from '../state/app.state';
import { Features } from '../../models/user.model';

export class CustomerSelectors {
  @Selector([ProcessState, CustomerState])
  static getUsers(processState: ProcessStateModel, customerState: CustomerStateModel) {
    return (processId: number) => {
      const customerIds = processState.processes[processId].customerIds;
      const customers = customerIds.map((t) => customerState.customers[t]);
      return customers;
    };
  }

  @Selector([ProcessState, CustomerState])
  static getActiveUser(processState: ProcessStateModel, customerState: CustomerStateModel) {
    return (processId: number) => {
      const activeCustomerId = processState.processes[processId].activeCustomer;
      return customerState.customers[activeCustomerId];
    };
  }

  @Selector([AppState, ProcessState, CustomerState])
  static getCurrentProcessActiveUser(appState: AppStateModel, processState: ProcessStateModel, customerState: CustomerStateModel) {
    const activeCustomerId = processState.processes[appState.currentProcesssId].activeCustomer;
    return customerState.customers[activeCustomerId];
  }

  @Selector([CustomerState])
  static getCustomerFeatures(customerState: CustomerStateModel) {
    return (customerId: number): Features[] => {
      return customerState.customers[customerId] ? customerState.customers[customerId].features : undefined;
    };
  }

  @Selector([CustomerState])
  static getCustomerLastCreatedCustomerId(customerState: CustomerStateModel) {
    return customerState.lastCreatedCustomerId;
  }

  @Selector([AppState, CustomerState])
  static getCachedCustomers(state: AppStateModel, customerState: CustomerStateModel) {
    const currentProcessId = state.currentProcesssId;

    return customerState.cachedCustomerSearch
      ? customerState.cachedCustomerSearch[currentProcessId]
        ? customerState.cachedCustomerSearch[currentProcessId]
        : null
      : null;
  }
}
