import { SYSTEM } from "../config/system.mjs"
import { abilitySchema, booleanField, conditionSchema, htmlField, numberField, stringField, trackSchema } from "./shared.mjs"

export default class MGNECharacter extends foundry.abstract.TypeDataModel {
  static defineSchema() {
    const fields = foundry.data.fields

    return {
      abilities: abilitySchema(),
      hp: trackSchema(1, 1),
      omens: new fields.SchemaField({
        current: numberField(0, 0),
        die: new fields.StringField({ required: true, nullable: false, initial: "d2", choices: SYSTEM.omenDieChoices }),
      }),
      resonance: new fields.SchemaField({
        max: numberField(1, 0),
        used: numberField(0, 0),
        blocked: booleanField(false),
      }),
      artifactSync: new fields.SchemaField({
        used: numberField(0, 0),
      }),
      survival: new fields.SchemaField({
        salvationUsed: booleanField(false),
      }),
      conditions: conditionSchema(),
      carryCapacity: numberField(8, 0),
      rations: numberField(0, 0),
      kiffol: numberField(0, 0),
      background: stringField(""),
      origin: stringField(""),
      scars: stringField(""),
      motivation: stringField(""),
      vice: stringField(""),
      description: htmlField(""),
      notes: htmlField(""),
    }
  }

  prepareDerivedData() {
    super.prepareDerivedData()

    this.carryCapacity = (this.abilities.strength?.value ?? 0) + 8
    this.resonance.remaining = Math.max(0, (this.resonance.max ?? 0) - (this.resonance.used ?? 0))
    this.syncLimit = Math.max(0, this.abilities.toughness?.value ?? 0)
    this.syncRemaining = Math.max(0, this.syncLimit - (this.artifactSync.used ?? 0))
    this.armorFormula = this.parent?.getArmorRollFormula?.() ?? "0"
  }

  /** @override */
  static LOCALIZATION_PREFIXES = ["MGNE.Character"]
}
