using System;
using System.Collections.Generic;

namespace Sonex.Client.Data
{
    public sealed class DataColumnByteArray : DataColumnBase
    {
        public List<byte[]?> Values { get; } = new();

        public override Type DataType => typeof(byte[]);
        public override int RowCount => Values.Count;

        public DataColumnByteArray(string key, string header, int initialRowCount = 0)
            : base(key, header)
        {
            ValueFormat = "HEX";

            for (int i = 0; i < initialRowCount; i++)
                Values.Add(null);
        }

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

            return Convert.ToHexString(value);
        }

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

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

            string hex = NormalizeHex(value);

            try
            {
                Values[rowIndex] = Convert.FromHexString(hex);
            }
            catch
            {
                throw new FormatException($"Value '{value}' is not a valid hex byte array.");
            }
        }

        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 byte[] bytes)
            {
                Values[rowIndex] = bytes;
                return;
            }

            throw new InvalidCastException($"Column '{Key}' expects byte[].");
        }

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

        private static string NormalizeHex(string value)
        {
            string hex = value.Trim()
                .Replace(" ", "")
                .Replace("-", "");

            if (hex.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                hex = hex[2..];

            return hex;
        }
    }
}