export const onOff = {
  false: "off",
  true: "on",
}

export const onOffTemp = {
  0: "off",
  1: "on",
  ...Object.fromEntries(Array.from({ length: 26 }, (_, i) => [i + 2, `${i + 15}`]))
}

export const precond = {
  0: "battery",
  1: "all",
  2: "climate",
  3: "stop"
}

export const hmol = {
  0: "off",
  1: "low",
  2: "mid",
  3: "high"
}

export const emptyCommands = [
  "doors_lock", "doors_unlock", "trunk_close", "flash_headlights", "alert"
]

export const onOffCommands = ["california_mode", "steering_wheel_preheat", "defrost", "charging"]

export const hmolCommands = ["passenger_seat_preheat", "driver_seat_preheat"]


const removeIfFieldsAreEmpty = (cmd, fields) => {
  for (const field of fields) {
    if (cmd[field] == null) {
      delete cmd[field]
    }
  }

  return cmd
}

const tempCabinPeriodConvert = (cmd) => {
  if (cmd.data == null || typeof cmd.data !== "number" || cmd.data < 0 || cmd.data > 27) {
    cmd.data = 0
  }

  cmd.data = onOffTemp[cmd.data]

  return cmd
}

const onOffConvert = (cmd) => {
  if (cmd.data == null || cmd.data !== true) {
    cmd.data = false
  }

  cmd.data = onOff[cmd.data]

  return cmd
}

const precondConvert = cmd => {
  if (cmd.data == null || typeof cmd.data !== "number" || cmd.data < 0 || cmd.data > 3) {
    cmd.data = 0
  }

  cmd.data = precond[cmd.data]

  return cmd
}

const hmolConvert = (cmd) => {
  if (cmd.data == null || typeof cmd.data !== "number" || cmd.data < 0 || cmd.data > 3) {
    cmd.data = 0
  }

  cmd.data = hmol[cmd.data]

  return cmd
}

const trunkOpenConvert = (cmd) => {
  if (cmd.data == null || typeof cmd.data !== "number" || cmd.data < 1 || cmd.data > 5) {
    cmd.data = 1
  }

  cmd.data = cmd.data.toString()

  return cmd
}

export const sanitize = (cmd) => {
  cmd = removeIfFieldsAreEmpty(cmd, ["data", "start", "end"])

  if (onOffCommands.includes(cmd.command)) {
    cmd = onOffConvert(cmd)
  } else if (hmolCommands.includes(cmd.command)) {
    cmd = hmolConvert(cmd)
  } else if (cmd.command === "precondition") {
    cmd = precondConvert(cmd)
  } else if (cmd.command === "trunk_open") {
    cmd = trunkOpenConvert(cmd)
  } else if (cmd.command === "temp_cabin") {
    cmd = tempCabinPeriodConvert(cmd)
  } else {
    delete cmd.data;
  }

  return cmd
}
