package database

import (
	"fmt"
	"time"

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

type CheckedInGuest struct {
	IDDocumentType      string
	IDDocumentNumber    string
	IDDocumentIssueDate time.Time
	GivenName           string
	FirstSurname        string
	SecondSurname       string
	Sex                 string
	Birthdate           time.Time
	CountryCode         string
	Phone               string
	Address             string
}

func (src CheckedInGuest) EncodeBinary(ci *pgtype.ConnInfo, dst []byte) ([]byte, error) {
	typeName := CheckedInGuestTypeName
	dt, ok := ci.DataTypeForName(typeName)
	if !ok {
		return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
	}
	var idDocumentIssueDate interface{}
	var noDate time.Time
	if src.IDDocumentIssueDate != noDate {
		idDocumentIssueDate = src.IDDocumentIssueDate
	}
	values := []interface{}{
		src.IDDocumentType,
		src.IDDocumentNumber,
		idDocumentIssueDate,
		src.GivenName,
		src.FirstSurname,
		src.SecondSurname,
		src.Sex,
		src.Birthdate,
		src.CountryCode,
		src.Phone,
		src.Address,
	}
	ct := pgtype.NewValue(dt.Value).(*pgtype.CompositeType)
	if err := ct.Set(values); err != nil {
		return nil, err
	}
	return ct.EncodeBinary(ci, dst)
}

type CheckedInGuestArray []*CheckedInGuest

func (src CheckedInGuestArray) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) {
	typeName := CheckedInGuestTypeName
	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
}