using Npgsql;
using NpgsqlTypes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper5.Data.PostgreSql
{
    internal static class NpgsqlParameterCollectionExtensions
    {
        public static void CheckNulls(this NpgsqlParameterCollection collection)
        {
            foreach (NpgsqlParameter o in collection)
            {
                if (o.Value == null)
                    o.Value = DBNull.Value;
                else if (o.Value == DBNull.Value)
                    continue;
                else
                {
                    if (o.NpgsqlDbType == NpgsqlDbType.Text || o.NpgsqlDbType == NpgsqlDbType.Varchar)
                    {
                        string oValue = (string)o.Value;
                        oValue = oValue.Trim('\0');
                        o.Value = oValue;
                    }
                }
            }
        }

        public static void AddParameter(this NpgsqlParameterCollection collection, string parameterName, NpgsqlDbType columnType, object value)
        {
            if (value == null)
            {
                collection.AddWithValue(parameterName, columnType, DBNull.Value);
            }
            else
            {
                if (value is ushort && columnType == NpgsqlDbType.Integer)
                {
                    collection.AddWithValue(parameterName, columnType, Convert.ToInt32((ushort)value));
                }
                else if (value is uint && columnType == NpgsqlDbType.Bigint)
                {
                    collection.AddWithValue(parameterName, columnType, Convert.ToInt64((uint)value));
                }
                else
                {
                    collection.AddWithValue(parameterName, columnType, value);
                }

                if (value is string)
                {
                    string s = (string)value;
                    if (s.Contains("\0"))
                        s = s.Replace("\0", "");
                }
            }
        }

        public static byte[] GetByteArray(this NpgsqlDataReader dataReader, int ordinal)
        {
            if (dataReader.IsDBNull(ordinal))
                return null;

            Stream stream = dataReader.GetStream(ordinal);
            byte[] buffer = new byte[stream.Length];
            if (stream.Read(buffer, 0, buffer.Length) != buffer.Length)
                throw new IOException("failed to read stream");
            stream.Close();
            return buffer;
        }

        public static void SetAllNull(this NpgsqlParameterCollection collection)
        {
            foreach (NpgsqlParameter o in collection)
            {
                o.Value = DBNull.Value;
            }
        }
    }

}
