using System;
using System.Collections.Generic;

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

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

        public DataColumnTimeSpan(string key, string header, int initialRowCount = 0)
            : base(key, header)
        {
            ValueFormat = @"hh\:mm\:ss";

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

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

            return value.Value.ToString(
                string.IsNullOrWhiteSpace(ValueFormat)
                    ? @"hh\:mm\:ss"
                    : ValueFormat);
        }

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

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

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

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

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

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