// The codecs of enums whose cases hold values (design F7 of add-xaml-codecs and G11 of add-xaml-generator).

///|
/// The cases of a choice, for the function that `XamlCodec::choice` takes.
pub struct XamlChoice[T] {
  priv registry : Registry
  priv cases : Array[ChoiceCase[T]]
  /// The case that takes each XAML type.
  priv by_type : Map[@nodes.XamlTypeName, ChoiceCase[T]]
}

///|
priv struct ChoiceCase[T] {
  to_xaml : (T) -> @nodes.XamlValue? raise
  from_xaml : (@nodes.XamlValue) -> T raise
  check : (@nodes.XamlValue) -> Unit raise
}

///|
/// How many choices can be inside each other before it is an error. Only a choice that has itself as a case comes this far.
let max_choice_depth : Int32 = 32

///|
/// Describe an enum whose cases hold values. A member or list with it takes the XAML types of all cases, and the type of an object
/// selects the case. `describe` adds the cases.
pub fn[T] XamlCodec::choice(describe : (XamlChoice[T]) -> Unit) -> XamlCodec[T] {
  // Those of the last registration. Each one gives the same, and puts the types of the cases in its schema context.
  let cases : Ref[Array[ChoiceCase[T]]] = Ref([])
  let by_type : Ref[Map[@nodes.XamlTypeName, ChoiceCase[T]]] = Ref(Map([]))
  let case_of = value => {
    guard @schema.value_type_name(value) is Some(name) &&
      by_type.val.get(name) is Some(found) else {
      raise @schema.ValueError("no case takes \{describe_value(value)}")
    }
    found
  }
  {
    type_name: @schema.object_type,
    value_types: () => by_type.val.keys().collect(),
    nullable: false,
    missing: None,
    is_leaf: false,
    to_label: None,
    problem: None,
    register: registry => {
      guard !registry.has_endless_choice else { return }
      if registry.choice_depth == max_choice_depth {
        registry.has_endless_choice = true
        registry.add_problem("a choice has itself as a case")
        return
      }
      registry.choice_depth += 1
      let choice = { registry, cases: [], by_type: Map([]), }
      describe(choice)
      registry.choice_depth -= 1
      cases.val = choice.cases
      by_type.val = choice.by_type
    },
    to_xaml: value => {
      for case_ in cases.val {
        if (case_.to_xaml)(value) is Some(found) {
          return found
        }
      }
      raise @schema.ValueError("no case has the value")
    },
    from_xaml: value => (case_of(value).from_xaml)(value),
    check: value => (case_of(value).check)(value),
    context: Ref(None),
  }
}

///|
/// Add the case that is written as the value of type `V` that it holds. `wrap` puts one in the enum, and `unwrap` takes it out or
/// gives `None` for another case. Each case needs XAML types of its own.
pub fn[T, V : Xaml] XamlChoice::add_case(
  self : XamlChoice[T],
  wrap : (V) -> T,
  unwrap : (T) -> V?,
) -> Unit {
  let codec : XamlCodec[V] = Xaml::xaml_codec()
  (codec.register)(self.registry)
  if codec.nullable {
    self.registry.add_problem(
      "a case of a choice cannot have optional values of the type \{codec.type_name}",
    )
  }
  self.add((codec.value_types)(), {
    to_xaml: value => {
      match unwrap(value) {
        Some(found) => Some((codec.to_xaml)(found))
        None => None
      }
    },
    from_xaml: value => wrap((codec.from_xaml)(value)),
    check: codec.check,
  })
}

///|
/// Add a case that is an element of its own, with the XAML name of `key`.
///
/// `unwrap` gives the values that the case holds, or `None` for another case. Several values can be a tuple. `describe` adds the
/// members that read from them, and gives the function that creates the case, as for `XamlKey::object`.
pub fn[T, P] XamlChoice::add_object(
  self : XamlChoice[T],
  key : XamlKey[T],
  unwrap : (T) -> P?,
  describe : (XamlObjectType[P]) -> (Members) -> T raise,
) -> Unit {
  let codec = key.part(unwrap, describe)
  (codec.register)(self.registry)
  self.add([key.type_name], {
    to_xaml: value => {
      if unwrap(value) is Some(_) {
        Some((codec.to_xaml)(value))
      } else {
        None
      }
    },
    from_xaml: codec.from_xaml,
    check: codec.check,
  })
}

///|
/// Add a case without values, which is an empty element with the XAML name of `key`. `value` is the case, and `is_case` says whether a
/// value is it. Such values are all the same in XAML, so they are never written as references.
pub fn[T] XamlChoice::add_constant(
  self : XamlChoice[T],
  key : XamlKey[T],
  value : T,
  is_case : (T) -> Bool,
) -> Unit {
  let { type_name, values, .. } = key
  key.equal.val = (_, _) => true
  let codec = key.object(_ => _ => value)
  (codec.register)(self.registry)
  self.add([type_name], {
    to_xaml: value => {
      if is_case(value) {
        Some(Object(values.wrap(type_name, value)))
      } else {
        None
      }
    },
    from_xaml: _ => value,
    check: codec.check,
  })
}

///|
/// Add a case that takes objects of the types `names`.
fn[T] XamlChoice::add(
  self : XamlChoice[T],
  names : Array[@nodes.XamlTypeName],
  added : ChoiceCase[T],
) -> Unit {
  for name in names {
    if self.by_type.contains(name) {
      self.registry.add_problem(
        "two cases of a choice have the type \{name}, so an object cannot select one",
      )
    }
    self.by_type[name] = added
  }
  self.cases.push(added)
}