using System;
using System.Collections.Generic;
using System.IO;
using Vellum;
namespace Clave.Vellum
{
///
/// Saves a KeyFormula as a list of terms, each one line of text that spells the keys that must all hold. The
/// formula matches when any term does.
///
///
/// The terms are written with key and space names, never the numbers a formula's diagram asks about, so a save
/// outlives a change to how those are numbered. See for the spelling.
///
public sealed class KeyFormulaConverter : SaveConverter
{
///
/// The most terms a formula may write. A formula that needs more fails to save instead of making a file nobody
/// can read.
///
public const int MaxTerms = 1024;
///
/// Returns the list of terms that is saved as.
///
public static SaveNode ToTermsNode(KeyFormula value)
{
SaveNode returnMe = SaveNode.NewList();
foreach (KeyLiteral[] term in value.ToTerms(MaxTerms))
{
returnMe.Items.Add(SaveNode.OfText(KeyTermText.Format(term)));
}
return returnMe;
}
///
/// Returns the formula that the list of terms in spells.
///
/// The node isn't a list of terms.
public static KeyFormula FromTermsNode(SaveNode node)
{
IReadOnlyList saved = node.RequireItems();
var terms = new List>(saved.Count);
for (int i = 0; i < saved.Count; ++i)
{
string text = saved[i].Text;
if (text == null)
{
throw new InvalidDataException("Term " + i + " of a saved key formula isn't text.");
}
terms.Add(KeyTermText.Parse(text));
}
return KeyFormula.FromTerms(terms);
}
public override SaveNode Write(KeyFormula value, SaveSession session)
{
return ToTermsNode(value);
}
public override KeyFormula Read(SaveNode node, SaveSession session)
{
return FromTermsNode(node);
}
public override bool TryListChildren(SaveNode node, ChildList children)
{
// Everything it reads is built-in, and so left out.
IReadOnlyList items;
return node.TryGetItems(out items);
}
}
}