using System.Diagnostics;
using Npgsql.BackendMessages;
using Npgsql.Internal.TypeHandling;
using Npgsql.PostgresTypes;
using NpgsqlTypes;

namespace Npgsql.Internal.TypeHandlers.InternalTypeHandlers;

partial class TidHandler : NpgsqlSimpleTypeHandler<NpgsqlTid>
{
    public TidHandler(PostgresType pgType) : base(pgType) {}

    #region Read

    public override NpgsqlTid Read(NpgsqlReadBuffer buf, int len, FieldDescription? fieldDescription = null)
    {
        Debug.Assert(len == 6);

        var blockNumber = buf.ReadUInt32();
        var offsetNumber = buf.ReadUInt16();

        return new NpgsqlTid(blockNumber, offsetNumber);
    }

    #endregion Read

    #region Write

    public override int ValidateAndGetLength(NpgsqlTid value, NpgsqlParameter? parameter)
        => 6;

    public override void Write(NpgsqlTid value, NpgsqlWriteBuffer buf, NpgsqlParameter? parameter)
    {
        buf.WriteUInt32(value.BlockNumber);
        buf.WriteUInt16(value.OffsetNumber);
    }

    #endregion Write
}

partial class TidHandler
{
    public override int ValidateObjectAndGetLength(object value, ref NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter)
        => value switch
        {

            NpgsqlTid converted => ((INpgsqlSimpleTypeHandler<NpgsqlTid>)this).ValidateAndGetLength(converted, parameter),


            _ => throw new InvalidCastException($"Can't write CLR type {value.GetType()} with handler type TidHandler")
        };

    public override Task WriteObjectWithLength(object? value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async, CancellationToken cancellationToken = default)
        => value switch
        {

            NpgsqlTid converted => WriteWithLength(converted, buf, lengthCache, parameter, async, cancellationToken),


            DBNull => WriteWithLength(DBNull.Value, buf, lengthCache, parameter, async, cancellationToken),
            null => WriteWithLength(DBNull.Value, buf, lengthCache, parameter, async, cancellationToken),
            _ => throw new InvalidCastException($"Can't write CLR type {value.GetType()} with handler type TidHandler")
        };
}