0
0
RhSolutions-Api/RhSolutions.Api/Models/Sku.cs

127 lines
3.4 KiB
C#
Raw Normal View History

2022-12-14 09:53:10 +03:00
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace RhSolutions.Api.Models
{
public class Sku
{
private const string matchPattern = @"([1\D]|\b)(?<Article>\d{6})([1\s-]|)(?<Variant>\d{3})\b";
private string? _article;
private string? _variant;
public Sku(string article, string variant)
{
Article = article;
Variant = variant;
}
[Key]
public string Id
{
get
{
return $"1{Article}1{Variant}";
}
set
{
if (TryParse(value, out IEnumerable<Sku> skus))
{
if (skus.Count() > 1)
{
throw new ArgumentException($"More than one valid sku detected: {value}");
}
else
{
this.Article = skus.First().Article;
this.Variant = skus.First().Variant;
}
}
else
{
throw new ArgumentException($"Invalid sku input: {value}");
}
}
}
public string? Article
{
get
{
return _article;
}
set
{
if (value == null || value.Length != 6 || value.Where(c => char.IsDigit(c)).Count() != 6)
{
throw new ArgumentException($"Wrong Article: {Article}");
}
else
{
_article = value;
}
}
}
public string? Variant
{
get
{
return _variant;
}
set
{
if (value == null || value.Length != 3 || value.Where(c => char.IsDigit(c)).Count() != 3)
{
throw new ArgumentException($"Wrong Variant: {Variant}");
}
else _variant = value;
}
}
public static IEnumerable<Sku> GetValidSkus(string line)
{
MatchCollection matches = Regex.Matches(line, matchPattern);
if (matches.Count == 0)
{
yield break;
}
else
{
foreach (Match m in matches)
{
yield return new Sku(m.Groups["Article"].Value, m.Groups["Variant"].Value);
}
}
}
public static bool TryParse(string line, out IEnumerable<Sku> skus)
{
MatchCollection matches = Regex.Matches(line, matchPattern);
if (matches.Count == 0)
{
skus = Enumerable.Empty<Sku>();
return false;
}
else
{
skus = GetValidSkus(line);
return true;
}
}
public override bool Equals(object? obj)
{
return obj is Sku sku &&
Article!.Equals(sku.Article) &&
Variant!.Equals(sku.Variant);
}
public override int GetHashCode()
{
return HashCode.Combine(Article, Variant);
}
public override string ToString()
{
return $"1{Article}1{Variant}";
}
}
}