using System;
using System.Collections.Generic;

namespace Sonex.Client.Data
{
    public sealed class DataColumnUInt : DataColumnBase
    {
        public List<uint?> Values { get; } = new();

        public override Type DataType => typeof(uint);
        public override int RowCount => Values.Count;

        public DataColumnUInt(string key, string header, int initialRowCount = 0)
            : base(key, header)
        {
            for (int i = 0; i < initialRowCount; i++)
                Values.Add(null);
        }

        protected override string? FormatValue(int rowIndex)
        {
            uint? value = Values[rowIndex];
            if (value is null)
                return null;

            return string.IsNullOrWhiteSpace(ValueFormat)
                ? value.Value.ToString()
                : value.Value.ToString(ValueFormat);
        }

        public override void SetValue(int rowIndex, string? value)
        {
            ValidateRowIndex(rowIndex);

            if (string.IsNullOrWhiteSpace(value))
            {
                Values[rowIndex] = null;
                return;
            }

            if (!uint.TryParse(value, out uint result))
                throw new FormatException($"Value '{value}' is not a valid uint.");

            Values[rowIndex] = result;
        }

        public override object? GetRawValue(int rowIndex)
        {
            ValidateRowIndex(rowIndex);
            return Values[rowIndex];
        }

        public override void SetRawValue(int rowIndex, object? value)
        {
            ValidateRowIndex(rowIndex);

            if (value is null)
            {
                Values[rowIndex] = null;
                return;
            }

            if (value is uint uintValue)
            {
                Values[rowIndex] = uintValue;
                return;
            }

            throw new InvalidCastException($"Column '{Key}' expects uint.");
        }

        public override void AddEmpty()
        {
            Values.Add(null);
        }
    }
}