package common

import (
	
	
	
	
)

const PageHeaderSize = unsafe.Sizeof(Page{})

const MinKeysPerPage = 2

const BranchPageElementSize = unsafe.Sizeof(branchPageElement{})
const LeafPageElementSize = unsafe.Sizeof(leafPageElement{})
const pgidSize = unsafe.Sizeof(Pgid(0))

const (
	BranchPageFlag   = 0x01
	LeafPageFlag     = 0x02
	MetaPageFlag     = 0x04
	FreelistPageFlag = 0x10
)

const (
	BucketLeafFlag = 0x01
)

type Pgid uint64

type Page struct {
	id       Pgid
	flags    uint16
	count    uint16
	overflow uint32
}

func ( Pgid, ,  uint16,  uint32) *Page {
	return &Page{
		id:       ,
		flags:    ,
		count:    ,
		overflow: ,
	}
}

// Typ returns a human-readable page type string used for debugging.
func ( *Page) () string {
	if .IsBranchPage() {
		return "branch"
	} else if .IsLeafPage() {
		return "leaf"
	} else if .IsMetaPage() {
		return "meta"
	} else if .IsFreelistPage() {
		return "freelist"
	}
	return fmt.Sprintf("unknown<%02x>", .flags)
}

func ( *Page) () bool {
	return .flags == BranchPageFlag
}

func ( *Page) () bool {
	return .flags == LeafPageFlag
}

func ( *Page) () bool {
	return .flags == MetaPageFlag
}

func ( *Page) () bool {
	return .flags == FreelistPageFlag
}

// IsValidPage checks Page flags correctness, only a single proper flag can be used.
func ( *Page) () bool {
	return .IsBranchPage() ||
		.IsLeafPage() ||
		.IsMetaPage() ||
		.IsFreelistPage()
}

// Meta returns a pointer to the metadata section of the page.
func ( *Page) () *Meta {
	return (*Meta)(UnsafeAdd(unsafe.Pointer(), unsafe.Sizeof(*)))
}

func ( *Page) ( Pgid) {
	if .id !=  {
		panic(fmt.Sprintf("assertion failed: Page expected to be: %v, but self identifies as %v", , .id))
	}
	// Only one flag of page-type can be set.
	if !.IsValidPage() {
		panic(fmt.Sprintf("assertion failed: page %v: has unexpected type/flags: %x", .id, .flags))
	}
}

// LeafPageElement retrieves the leaf node by index
func ( *Page) ( uint16) *leafPageElement {
	return (*leafPageElement)(UnsafeIndex(unsafe.Pointer(), unsafe.Sizeof(*),
		LeafPageElementSize, int()))
}

// LeafPageElements retrieves a list of leaf nodes.
func ( *Page) () []leafPageElement {
	if .count == 0 {
		return nil
	}
	 := UnsafeAdd(unsafe.Pointer(), unsafe.Sizeof(*))
	 := unsafe.Slice((*leafPageElement)(), int(.count))
	return 
}

// BranchPageElement retrieves the branch node by index
func ( *Page) ( uint16) *branchPageElement {
	return (*branchPageElement)(UnsafeIndex(unsafe.Pointer(), unsafe.Sizeof(*),
		unsafe.Sizeof(branchPageElement{}), int()))
}

// BranchPageElements retrieves a list of branch nodes.
func ( *Page) () []branchPageElement {
	if .count == 0 {
		return nil
	}
	 := UnsafeAdd(unsafe.Pointer(), unsafe.Sizeof(*))
	 := unsafe.Slice((*branchPageElement)(), int(.count))
	return 
}

func ( *Page) () (int, int) {
	if !.IsFreelistPage() {
		panic(fmt.Sprintf("assertion failed: can't get freelist page count from a non-freelist page: %2x", .flags))
	}

	// If the page.count is at the max uint16 value (64k) then it's considered
	// an overflow and the size of the freelist is stored as the first element.
	var ,  = 0, int(.count)
	if  == 0xFFFF {
		 = 1
		 := *(*Pgid)(UnsafeAdd(unsafe.Pointer(), unsafe.Sizeof(*)))
		 = int()
		if  < 0 {
			panic(fmt.Sprintf("leading element count %d overflows int", ))
		}
	}

	return , 
}

func ( *Page) () []Pgid {
	if !.IsFreelistPage() {
		panic(fmt.Sprintf("assertion failed: can't get freelist page IDs from a non-freelist page: %2x", .flags))
	}

	,  := .FreelistPageCount()

	if  == 0 {
		return nil
	}

	 := UnsafeIndex(unsafe.Pointer(), unsafe.Sizeof(*), pgidSize, )
	 := unsafe.Slice((*Pgid)(), )

	return 
}

// dump writes n bytes of the page to STDERR as hex output.
func ( *Page) ( int) {
	 := UnsafeByteSlice(unsafe.Pointer(), 0, 0, )
	fmt.Fprintf(os.Stderr, "%x\n", )
}

func ( *Page) () uintptr {
	if .IsLeafPage() {
		return LeafPageElementSize
	}
	return BranchPageElementSize
}

func ( *Page) () Pgid {
	return .id
}

func ( *Page) ( Pgid) {
	.id = 
}

func ( *Page) () uint16 {
	return .flags
}

func ( *Page) ( uint16) {
	.flags = 
}

func ( *Page) () uint16 {
	return .count
}

func ( *Page) ( uint16) {
	.count = 
}

func ( *Page) () uint32 {
	return .overflow
}

func ( *Page) ( uint32) {
	.overflow = 
}

func ( *Page) () string {
	return fmt.Sprintf("ID: %d, Type: %s, count: %d, overflow: %d", .id, .Typ(), .count, .overflow)
}

type Pages []*Page

func ( Pages) () int           { return len() }
func ( Pages) (,  int)      { [], [] = [], [] }
func ( Pages) (,  int) bool { return [].id < [].id }

// branchPageElement represents a node on a branch page.
type branchPageElement struct {
	pos   uint32
	ksize uint32
	pgid  Pgid
}

func ( *branchPageElement) () uint32 {
	return .pos
}

func ( *branchPageElement) ( uint32) {
	.pos = 
}

func ( *branchPageElement) () uint32 {
	return .ksize
}

func ( *branchPageElement) ( uint32) {
	.ksize = 
}

func ( *branchPageElement) () Pgid {
	return .pgid
}

func ( *branchPageElement) ( Pgid) {
	.pgid = 
}

// Key returns a byte slice of the node key.
func ( *branchPageElement) () []byte {
	return UnsafeByteSlice(unsafe.Pointer(), 0, int(.pos), int(.pos)+int(.ksize))
}

// leafPageElement represents a node on a leaf page.
type leafPageElement struct {
	flags uint32
	pos   uint32
	ksize uint32
	vsize uint32
}

func (, , ,  uint32) *leafPageElement {
	return &leafPageElement{
		flags: ,
		pos:   ,
		ksize: ,
		vsize: ,
	}
}

func ( *leafPageElement) () uint32 {
	return .flags
}

func ( *leafPageElement) ( uint32) {
	.flags = 
}

func ( *leafPageElement) () uint32 {
	return .pos
}

func ( *leafPageElement) ( uint32) {
	.pos = 
}

func ( *leafPageElement) () uint32 {
	return .ksize
}

func ( *leafPageElement) ( uint32) {
	.ksize = 
}

func ( *leafPageElement) () uint32 {
	return .vsize
}

func ( *leafPageElement) ( uint32) {
	.vsize = 
}

// Key returns a byte slice of the node key.
func ( *leafPageElement) () []byte {
	 := int(.pos)
	 :=  + int(.ksize)
	return UnsafeByteSlice(unsafe.Pointer(), 0, , )
}

// Value returns a byte slice of the node value.
func ( *leafPageElement) () []byte {
	 := int(.pos) + int(.ksize)
	 :=  + int(.vsize)
	return UnsafeByteSlice(unsafe.Pointer(), 0, , )
}

func ( *leafPageElement) () bool {
	return .flags&uint32(BucketLeafFlag) != 0
}

func ( *leafPageElement) () *InBucket {
	if .IsBucketEntry() {
		return LoadBucket(.Value())
	} else {
		return nil
	}
}

// PageInfo represents human readable information about a page.
type PageInfo struct {
	ID            int
	Type          string
	Count         int
	OverflowCount int
}

type Pgids []Pgid

func ( Pgids) () int           { return len() }
func ( Pgids) (,  int)      { [], [] = [], [] }
func ( Pgids) (,  int) bool { return [] < [] }

// Merge returns the sorted union of a and b.
func ( Pgids) ( Pgids) Pgids {
	// Return the opposite slice if one is nil.
	if len() == 0 {
		return 
	}
	if len() == 0 {
		return 
	}
	 := make(Pgids, len()+len())
	Mergepgids(, , )
	return 
}

// Mergepgids copies the sorted union of a and b into dst.
// If dst is too small, it panics.
func (, ,  Pgids) {
	if len() < len()+len() {
		panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(), len(), len()))
	}
	// Copy in the opposite slice if one is nil.
	if len() == 0 {
		copy(, )
		return
	}
	if len() == 0 {
		copy(, )
		return
	}

	// Merged will hold all elements from both lists.
	 := [:0]

	// Assign lead to the slice with a lower starting value, follow to the higher value.
	,  := , 
	if [0] < [0] {
		,  = , 
	}

	// Continue while there are elements in the lead.
	for len() > 0 {
		// Merge largest prefix of lead that is ahead of follow[0].
		 := sort.Search(len(), func( int) bool { return [] > [0] })
		 = append(, [:]...)
		if  >= len() {
			break
		}

		// Swap lead and follow.
		,  = , [:]
	}

	// Append what's left in follow.
	_ = append(, ...)
}