using System.Text.RegularExpressions;
using Comal.Classes;
using InABox.Core;
using InABox.Database;
namespace PRS.Shared;
///
/// Trigger the calculation of Digital Form Numbers
///
/// true (always)
public class Update_7_19 : DatabaseUpdateScript
{
public override VersionNumber Version => new VersionNumber(7, 19);
public override bool Update()
{
// Find all classes that derive from EntityForm
var formtypes = CoreUtils.TypeList(
new[]
{
typeof(Setout).Assembly
},
myType =>
myType is { IsClass: true, IsAbstract: false, IsGenericType: false }
&& myType.IsSubclassOf(typeof(Entity))
&& myType.GetInterfaces().Contains(typeof(IEntityForm))
).ToArray();
foreach (var formtype in formtypes)
{
var columns = Columns.None(formtype).Add("ID").Add("Number");
var forms = DbFactory.NewProvider(Logger.Main).Query(formtype, null, columns);
var nullforms = forms.Rows
.Where(r => String.IsNullOrWhiteSpace(r.Get("Number")))
.Select(r=>r.ToObject(formtype))
.OfType()
.ToArray();
if (!nullforms.Any())
continue;
var maxvalue = forms.Rows.Select(r => Regex.Match(r.Get("Number") ?? "", @"(?<=-)\d+")?.Value ?? "0")
.MaxBy(x => x) ?? "0";
int.TryParse(maxvalue, out int iNumber);
String prefix = null;
String format = null;
foreach (var form in nullforms)
{
prefix ??= (form as IStringAutoIncrement)?.AutoIncrementPrefix() ?? "";
format ??= (form as IStringAutoIncrement)?.AutoIncrementFormat() ?? "{0:D8}";
iNumber++;
CoreUtils.SetPropertyValue(form, "Number", prefix+String.Format(format, iNumber));
}
DbFactory.NewProvider(Logger.Main).Save(formtype, nullforms);
}
return true;
}
}