using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
using System.Data;

namespace PhilExampleCrawler.DataBase
{
    internal static class Extensions
    {
        internal static string WriteNullableString(object? value)
        {
            return value == null ? "null"
                                 : "'" + value.ToString() + "'";
        }

        internal static string WriteNullableInt(int? value)
        {
            return !value.HasValue ? "null"
                                   : value.Value.ToString();
        }

        internal static string WriteNullableDateTime(DateTime? value)
        {
            return !value.HasValue ? "null"
                                   : "'" + value.Value.ToString("dd.MM.yyyy HH:mm:ss") + "'";
        }

        //TODO: or use a generic version?
        //internal static T? ReadNullable<T>(this DbDataReader r, string name) where T : struct
        //{
        //    var t = r.GetValue(name);
        //    if (t == DBNull.Value) return null;
        //    else return (T)t;
        //}

        internal static string? ReadNullableString(this DbDataReader r, string name)
        {
            var t = r.GetValue(name);
            if (t == DBNull.Value) return null;
            else return (string)t;
        }

        internal static bool? ReadNullableBoolean(this DbDataReader r, string name)
        {
            var t = r.GetValue(name);
            if (t == DBNull.Value) return null;
            else return (bool)t;
        }

        internal static int? ReadNullableInt(this DbDataReader r, string name)
        {
            var t = r.GetValue(name);
            if (t == DBNull.Value) return null;
            else return (int)t;
        }

        internal static DateTime? ReadNullableDateTime(this DbDataReader r, string name)
        {
            var t = r.GetValue(name);
            if (t == DBNull.Value) return null;
            else return (DateTime)t;
        }
    }
}
