namespace DataService;

public class DBProcessData<T_Hierarchy>(char spilter, int skip)
    where T_Hierarchy : IDictionary<string, object>, new()
{
    public bool ToDictionary(IDictionary<string, object> input, out T_Hierarchy? output)
    {
        output = default;

        if (input is null)
            return false;

        T_Hierarchy cache = [];
        foreach (KeyValuePair<string, object> rawData in input)
        {
            Span<string> source = rawData.Key.Split(spilter).AsSpan()[skip..];
            ColumAnalizer(cache, source, rawData.Value);
        }

        output = cache;
        return true;
    }

    private static void ColumAnalizer(/*ref*/ T_Hierarchy cache, Span<string> seprated, object value)
    {
        if (seprated.Length <= 1)
        {
            cache[seprated[0]] = value;
            return;
        }

        if (!cache.TryGetValue(seprated[0], out object? output) || output is not T_Hierarchy hierarchy)
        {
            hierarchy = [];
            cache[seprated[0]] = hierarchy;
        }

        cache = hierarchy;
        ColumAnalizer(cache, seprated[1..], value);
    }
}

public class GeneralProcessData(int skip = 0) : DBProcessData<Dictionary<string, object>>('.', skip)
{
}