using System;
using System.Collections.Generic;

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

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

        public DataColumnBool(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)
        {
            bool? value = Values[rowIndex];
            if (value is null)
                return null;

            return ValueFormat switch
            {
                "1/0" => value.Value ? "1" : "0",
                "Yes/No" => value.Value ? "Yes" : "No",
                _ => value.Value ? "True" : "False"
            };
        }

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

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

            switch (value.ToLower().Trim())
            {
                case "1":
                case "true":
                case "yes":
                case "ja":
                    Values[rowIndex] = true;
                    return;

                case "0":
                case "false":
                case "no":
                case "nee":
                    Values[rowIndex] = false;
                    return;
            }

            throw new FormatException($"Value '{value}' is not a valid bool.");
        }

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

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

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