Files
BeWoPlaner/Dakota/Models/Daten/Datenelement.cs
2025-11-05 13:24:03 +01:00

119 lines
2.3 KiB
C#

using BS.Shared.Exceptions;
using Dakota.Models.Schlüssels;
using System;
namespace Dakota.Models.Daten
{
internal class Datenelement : Dateneinheit
{
private protected string _Value;
private protected bool _IgnoreCheck;
public int MinStellen { get; set; }
public int MaxStellen { get; set; }
public Feldart Feldart { get; set; }
public Datenelement(string title)
{
Title = title;
_IgnoreCheck = false;
}
public Datenelement(string title, int min, int max, Feldart art) : this(title)
{
MinStellen = min;
MaxStellen = max;
Feldart = art;
}
public Datenelement(string title, int count, Feldart art) : this(title, count, count, art)
{
}
public override string GetValue()
{
if (!HasValue())
{
if (Feldart == Feldart.Muss)
{
// Auffüllen
throw new GkvException($"Das Feld \"{Title}\" muss gefüllt sein!");
}
else
{
// Leer lassen
return string.Empty;
}
}
if (!_IgnoreCheck)
{
CheckValue(_Value);
}
return _Value;
}
public void ClearValue()
{
_Value = null;
}
public override bool HasValue()
{
return !string.IsNullOrEmpty(_Value);
}
public void SetValue(int value)
{
if (Feldart == Feldart.Kann && value == 0)
return;
SetValue(value.ToString());
}
public void SetValue(Schlüssel schlussel)
{
if (schlussel is null)
return;
SetValue(schlussel.Value);
}
public void SetValue(string value)
{
if (value is null)
return;
value = value.Trim();
CheckValue(value);
try
{
var mod_value = DakotaUtils.ClearTextString(value);
_Value = mod_value;
}
catch (Exception e)
{
throw new Exception($"Fehler bei Feld \'{Title}\' mit Wert \"{value}\"", e);
}
}
private void CheckValue(string value)
{
if (value.Length < MinStellen)
{
throw GetGkvException(value, true);
}
else if (value.Length > MaxStellen)
{
throw GetGkvException(value, false);
}
}
private GkvException GetGkvException(string value, bool isLess)
=> new GkvException($"Das Feld \"{Title}\" hat bei der Erstellung {value.Length} Stellen ergeben! Nach Vorgabe " +
$"{(isLess ? $"muss es jedoch mindestens {MinStellen}" : $"darf es jedoch maximal {MaxStellen}")}" +
" Stellen haben");
}
}