import { SYSTEM } from "../config/system.mjs"

export function htmlField(initial = "", options = {}) {
  return new foundry.data.fields.HTMLField({ required: true, initial, textSearch: true, ...options })
}

export function stringField(initial = "", options = {}) {
  return new foundry.data.fields.StringField({ required: true, nullable: false, initial, ...options })
}

export function numberField(initial = 0, min = 0, max = null, options = {}) {
  return new foundry.data.fields.NumberField({
    required: true,
    nullable: false,
    integer: true,
    initial,
    min,
    ...(max === null ? {} : { max }),
    ...options,
  })
}

export function booleanField(initial = false, options = {}) {
  return new foundry.data.fields.BooleanField({ required: true, initial, ...options })
}

export function abilitySchema() {
  const fields = foundry.data.fields
  const schema = {}
  for (const abilityId of SYSTEM.abilityOrder) {
    const ability = SYSTEM.abilities[abilityId]
    schema[abilityId] = new fields.SchemaField(
      {
        label: stringField(ability.label, { label: "MGNE.Common.Label" }),
        value: numberField(0, -3, 6, { label: "MGNE.Common.Value" }),
      },
      { label: ability.label }
    )
  }
  return new fields.SchemaField(schema)
}

export function conditionSchema() {
  const fields = foundry.data.fields
  const schema = {}
  for (const condition of Object.values(SYSTEM.conditions)) {
    if (condition.hasValue) {
      schema[condition.id] = new fields.SchemaField(
        { value: numberField(0, 0, 12, { label: "MGNE.Common.Value" }) },
        { label: condition.label }
      )
    } else {
      schema[condition.id] = new fields.SchemaField(
        { active: booleanField(false, { label: condition.label }) },
        { label: condition.label }
      )
    }
  }
  return new fields.SchemaField(schema)
}

export function trackSchema(initialValue = 0, initialMax = 0) {
  return new foundry.data.fields.SchemaField({
    value: numberField(initialValue, -99),
    max: numberField(initialMax, 0),
  })
}
