package database

import (
	"fmt"

	"github.com/jackc/pgio"
	"github.com/jackc/pgtype"
)

type OptionUnits struct {
	OptionID int
	Units    int
}

func (src OptionUnits) EncodeBinary(ci *pgtype.ConnInfo, dst []byte) ([]byte, error) {
	typeName := OptionUnitsTypeName
	dt, ok := ci.DataTypeForName(typeName)
	if !ok {
		return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
	}
	values := []interface{}{
		src.OptionID,
		src.Units,
	}
	ct := pgtype.NewValue(dt.Value).(*pgtype.CompositeType)
	if err := ct.Set(values); err != nil {
		return nil, err
	}
	return ct.EncodeBinary(ci, dst)
}

type OptionUnitsArray []*OptionUnits

func (src OptionUnitsArray) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) {
	typeName := OptionUnitsTypeName
	dt, ok := ci.DataTypeForName(typeName)
	if !ok {
		return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
	}

	arrayHeader := pgtype.ArrayHeader{
		ElementOID: int32(dt.OID),
		Dimensions: []pgtype.ArrayDimension{{Length: int32(len(src)), LowerBound: 1}},
	}
	buf = arrayHeader.EncodeBinary(ci, buf)
	for _, optionUnits := range src {
		sp := len(buf)
		buf = pgio.AppendInt32(buf, -1)

		elemBuf, err := optionUnits.EncodeBinary(ci, buf)
		if err != nil {
			return nil, err
		}
		if elemBuf != nil {
			buf = elemBuf
			pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4))
		}
	}
	return buf, nil
}