/*
 * SPDX-FileCopyrightText: 2022 WGH <wgh@torlan.ru>
 * SPDX-License-Identifier: MIT
 */

package database

import (
	"encoding/binary"
	"fmt"
	"reflect"

	"github.com/jackc/pgtype"
)

type RecordArray struct {
	Elements   []pgtype.Record
	Dimensions []pgtype.ArrayDimension
	Status     pgtype.Status
}

func (dst *RecordArray) Set(src interface{}) error {
	// untyped nil and typed nil interfaces are different
	if src == nil {
		*dst = RecordArray{Status: pgtype.Null}
		return nil
	}

	if value, ok := src.(interface{ Get() interface{} }); ok {
		value2 := value.Get()
		if value2 != value {
			return dst.Set(value2)
		}
	}

	// Attempt to match to select common types:
	switch value := src.(type) {

	case [][]pgtype.Value:
		if value == nil {
			*dst = RecordArray{Status: pgtype.Null}
		} else if len(value) == 0 {
			*dst = RecordArray{Status: pgtype.Present}
		} else {
			elements := make([]pgtype.Record, len(value))
			for i := range value {
				if err := elements[i].Set(value[i]); err != nil {
					return err
				}
			}
			*dst = RecordArray{
				Elements:   elements,
				Dimensions: []pgtype.ArrayDimension{{Length: int32(len(elements)), LowerBound: 1}},
				Status:     pgtype.Present,
			}
		}

	case []pgtype.Record:
		if value == nil {
			*dst = RecordArray{Status: pgtype.Null}
		} else if len(value) == 0 {
			*dst = RecordArray{Status: pgtype.Present}
		} else {
			*dst = RecordArray{
				Elements:   value,
				Dimensions: []pgtype.ArrayDimension{{Length: int32(len(value)), LowerBound: 1}},
				Status:     pgtype.Present,
			}
		}
	default:
		// Fallback to reflection if an optimised match was not found.
		// The reflection is necessary for arrays and multidimensional slices,
		// but it comes with a 20-50% performance penalty for large arrays/slices
		reflectedValue := reflect.ValueOf(src)
		if !reflectedValue.IsValid() || reflectedValue.IsZero() {
			*dst = RecordArray{Status: pgtype.Null}
			return nil
		}

		dimensions, elementsLength, ok := findDimensionsFromValue(reflectedValue, nil, 0)
		if !ok {
			return fmt.Errorf("cannot find dimensions of %v for RecordArray", src)
		}
		if elementsLength == 0 {
			*dst = RecordArray{Status: pgtype.Present}
			return nil
		}
		if len(dimensions) == 0 {
			if originalSrc, ok := underlyingSliceType(src); ok {
				return dst.Set(originalSrc)
			}
			return fmt.Errorf("cannot convert %v to RecordArray", src)
		}

		*dst = RecordArray{
			Elements:   make([]pgtype.Record, elementsLength),
			Dimensions: dimensions,
			Status:     pgtype.Present,
		}
		elementCount, err := dst.setRecursive(reflectedValue, 0, 0)
		if err != nil {
			// Maybe the target was one dimension too far, try again:
			if len(dst.Dimensions) > 1 {
				dst.Dimensions = dst.Dimensions[:len(dst.Dimensions)-1]
				elementsLength = 0
				for _, dim := range dst.Dimensions {
					if elementsLength == 0 {
						elementsLength = int(dim.Length)
					} else {
						elementsLength *= int(dim.Length)
					}
				}
				dst.Elements = make([]pgtype.Record, elementsLength)
				elementCount, err = dst.setRecursive(reflectedValue, 0, 0)
				if err != nil {
					return err
				}
			} else {
				return err
			}
		}
		if elementCount != len(dst.Elements) {
			return fmt.Errorf("cannot convert %v to RecordArray, expected %d dst.Elements, but got %d instead", src, len(dst.Elements), elementCount)
		}
	}

	return nil
}

func (dst *RecordArray) setRecursive(value reflect.Value, index, dimension int) (int, error) {
	switch value.Kind() {
	case reflect.Array:
		fallthrough
	case reflect.Slice:
		if len(dst.Dimensions) == dimension {
			break
		}

		valueLen := value.Len()
		if int32(valueLen) != dst.Dimensions[dimension].Length {
			return 0, fmt.Errorf("multidimensional arrays must have array expressions with matching dimensions")
		}
		for i := 0; i < valueLen; i++ {
			var err error
			index, err = dst.setRecursive(value.Index(i), index, dimension+1)
			if err != nil {
				return 0, err
			}
		}

		return index, nil
	}
	if !value.CanInterface() {
		return 0, fmt.Errorf("cannot convert all values to RecordArray")
	}
	if err := dst.Elements[index].Set(value.Interface()); err != nil {
		return 0, fmt.Errorf("%v in RecordArray", err)
	}
	index++

	return index, nil
}

func (dst RecordArray) Get() interface{} {
	switch dst.Status {
	case pgtype.Present:
		return dst
	case pgtype.Null:
		return nil
	default:
		return dst.Status
	}
}

func (src *RecordArray) AssignTo(dst interface{}) error {
	switch src.Status {
	case pgtype.Present:
		if len(src.Dimensions) <= 1 {
			// Attempt to match to select common types:
			switch v := dst.(type) {

			case *[][]pgtype.Value:
				*v = make([][]pgtype.Value, len(src.Elements))
				for i := range src.Elements {
					if err := src.Elements[i].AssignTo(&((*v)[i])); err != nil {
						return err
					}
				}
				return nil

			}
		}

		// Try to convert to something AssignTo can use directly.
		if nextDst, retry := pgtype.GetAssignToDstType(dst); retry {
			return src.AssignTo(nextDst)
		}

		// Fallback to reflection if an optimised match was not found.
		// The reflection is necessary for arrays and multidimensional slices,
		// but it comes with a 20-50% performance penalty for large arrays/slices
		value := reflect.ValueOf(dst)
		if value.Kind() == reflect.Ptr {
			value = value.Elem()
		}

		switch value.Kind() {
		case reflect.Array, reflect.Slice:
		default:
			return fmt.Errorf("cannot assign %T to %T", src, dst)
		}

		if len(src.Elements) == 0 {
			if value.Kind() == reflect.Slice {
				value.Set(reflect.MakeSlice(value.Type(), 0, 0))
				return nil
			}
		}

		elementCount, err := src.assignToRecursive(value, 0, 0)
		if err != nil {
			return err
		}
		if elementCount != len(src.Elements) {
			return fmt.Errorf("cannot assign %v, needed to assign %d elements, but only assigned %d", dst, len(src.Elements), elementCount)
		}

		return nil
	case pgtype.Null:
		return pgtype.NullAssignTo(dst)
	}

	return fmt.Errorf("cannot decode %#v into %T", src, dst)
}

func (src *RecordArray) assignToRecursive(value reflect.Value, index, dimension int) (int, error) {
	switch kind := value.Kind(); kind {
	case reflect.Array:
		fallthrough
	case reflect.Slice:
		if len(src.Dimensions) == dimension {
			break
		}

		length := int(src.Dimensions[dimension].Length)
		if reflect.Array == kind {
			typ := value.Type()
			if typ.Len() != length {
				return 0, fmt.Errorf("expected size %d array, but %s has size %d array", length, typ, typ.Len())
			}
			value.Set(reflect.New(typ).Elem())
		} else {
			value.Set(reflect.MakeSlice(value.Type(), length, length))
		}

		var err error
		for i := 0; i < length; i++ {
			index, err = src.assignToRecursive(value.Index(i), index, dimension+1)
			if err != nil {
				return 0, err
			}
		}

		return index, nil
	}
	if len(src.Dimensions) != dimension {
		return 0, fmt.Errorf("incorrect dimensions, expected %d, found %d", len(src.Dimensions), dimension)
	}
	if !value.CanAddr() {
		return 0, fmt.Errorf("cannot assign all values from RecordArray")
	}
	addr := value.Addr()
	if !addr.CanInterface() {
		return 0, fmt.Errorf("cannot assign all values from RecordArray")
	}
	if err := src.Elements[index].AssignTo(addr.Interface()); err != nil {
		return 0, err
	}
	index++
	return index, nil
}

func (dst *RecordArray) DecodeBinary(ci *pgtype.ConnInfo, src []byte) error {
	if src == nil {
		*dst = RecordArray{Status: pgtype.Null}
		return nil
	}

	var arrayHeader pgtype.ArrayHeader
	rp, err := arrayHeader.DecodeBinary(ci, src)
	if err != nil {
		return err
	}

	if len(arrayHeader.Dimensions) == 0 {
		*dst = RecordArray{Dimensions: arrayHeader.Dimensions, Status: pgtype.Present}
		return nil
	}

	elementCount := arrayHeader.Dimensions[0].Length
	for _, d := range arrayHeader.Dimensions[1:] {
		elementCount *= d.Length
	}

	elements := make([]pgtype.Record, elementCount)

	for i := range elements {
		elemLen := int(int32(binary.BigEndian.Uint32(src[rp:])))
		rp += 4
		var elemSrc []byte
		if elemLen >= 0 {
			elemSrc = src[rp : rp+elemLen]
			rp += elemLen
		}
		err = elements[i].DecodeBinary(ci, elemSrc)
		if err != nil {
			return err
		}
	}

	*dst = RecordArray{Elements: elements, Dimensions: arrayHeader.Dimensions, Status: pgtype.Present}
	return nil
}

func underlyingSliceType(val interface{}) (interface{}, bool) {
	refVal := reflect.ValueOf(val)

	switch refVal.Kind() {
	case reflect.Ptr:
		if refVal.IsNil() {
			return nil, false
		}
		convVal := refVal.Elem().Interface()
		return convVal, true
	case reflect.Slice:
		baseSliceType := reflect.SliceOf(refVal.Type().Elem())
		if refVal.Type().ConvertibleTo(baseSliceType) {
			convVal := refVal.Convert(baseSliceType)
			return convVal.Interface(), reflect.TypeOf(convVal.Interface()) != refVal.Type()
		}
	}

	return nil, false
}

func findDimensionsFromValue(value reflect.Value, dimensions []pgtype.ArrayDimension, elementsLength int) ([]pgtype.ArrayDimension, int, bool) {
	switch value.Kind() {
	case reflect.Array:
		fallthrough
	case reflect.Slice:
		length := value.Len()
		if 0 == elementsLength {
			elementsLength = length
		} else {
			elementsLength *= length
		}
		dimensions = append(dimensions, pgtype.ArrayDimension{Length: int32(length), LowerBound: 1})
		for i := 0; i < length; i++ {
			if d, l, ok := findDimensionsFromValue(value.Index(i), dimensions, elementsLength); ok {
				return d, l, true
			}
		}
	}
	return dimensions, elementsLength, true
}