import { itemsMap } from '../../data/maps.js'
import { areHuggingMachinesInInventory } from '../../utils/areHuggingMachinesInInventory.js'
import { HUGGING_MACHINE_ITEM_ID } from '../../constants.js'

import { addItemToInventory } from './addItemToInventory.js'
import { decrementItemFromInventory } from './decrementItemFromInventory.js'
import { modifyCow } from './modifyCow.js'

export const changeCowAutomaticHugState = (
  state: farmhand.state,
  cow: farmhand.cow,
  doUseHuggingMachine: boolean
): farmhand.state => {
  if (doUseHuggingMachine) {
    if (
      cow.isUsingHuggingMachine ||
      !areHuggingMachinesInInventory(state.inventory)
    ) {
      return state
    }
  }

  state = modifyCow(state, cow.id, updatedCow => ({
    ...updatedCow,
    isUsingHuggingMachine: doUseHuggingMachine,
  }))

  state = doUseHuggingMachine
    ? decrementItemFromInventory(state, HUGGING_MACHINE_ITEM_ID)
    : addItemToInventory(state, itemsMap[HUGGING_MACHINE_ITEM_ID])

  return state
}
