package uv

import 

// hash returns the hash value of a [Line].
func ( *maphash.Hash,  Line) uint64 {
	.Reset()
	for ,  := range  {
		// maphash writes can not fail
		_, _ = .WriteString(.Content)
	}

	return .Sum64()
}

// hashmap represents a single [Line] hash.
type hashmap struct {
	value              uint64
	oldcount, newcount int
	oldindex, newindex int
}

// The value used to indicate lines created by insertions and scrolls.
const newIndex = -1

// updateHashmap updates the hashmap with the new hash value.
func ( *TerminalRenderer) ( *RenderBuffer) {
	 := .Height()

	if len(.oldhash) >=  && len(.newhash) >=  {
		// rehash changed lines
		for  := range  {
			if .Touched == nil || .Touched[] != nil {
				// TODO: Investigate why this is needed. If we remove this
				// line, scroll optimization does not work correctly. This
				// should happen else where.
				.oldhash[] = hash(&.hasher, .curbuf.Line())
				.newhash[] = hash(&.hasher, .Line())
			}
		}
	} else {
		// rehash all
		if len(.oldhash) !=  {
			.oldhash = make([]uint64, )
		}
		if len(.newhash) !=  {
			.newhash = make([]uint64, )
		}
		for  := range  {
			.oldhash[] = hash(&.hasher, .curbuf.Line())
			.newhash[] = hash(&.hasher, .Line())
		}
	}

	.hashtab = make([]hashmap, (+1)*2)
	for  := range  {
		 := .oldhash[]

		// Find matching hash or empty slot
		var  int
		for  = 0;  < len(.hashtab) && .hashtab[].value != 0; ++ {
			if .hashtab[].value ==  {
				break
			}
		}

		.hashtab[].value =  // in case this is a new hash
		.hashtab[].oldcount++
		.hashtab[].oldindex = 
	}
	for  := range  {
		 := .newhash[]

		// Find matching hash or empty slot
		var  int
		for  = 0;  < len(.hashtab) && .hashtab[].value != 0; ++ {
			if .hashtab[].value ==  {
				break
			}
		}

		.hashtab[].value =  // in case this is a new hash
		.hashtab[].newcount++
		.hashtab[].newindex = 
		.oldnum[] = newIndex // init old indices slice
	}

	// Mark line pair corresponding to unique hash pairs.
	for  := 0;  < len(.hashtab) && .hashtab[].value != 0; ++ {
		 := &.hashtab[]
		if .oldcount == 1 && .newcount == 1 && .oldindex != .newindex {
			.oldnum[.newindex] = .oldindex
		}
	}

	.growHunks()

	// Eliminate bad or impossible shifts. This includes removing those hunks
	// which could not grow because of conflicts, as well those which are to be
	// moved too far, they are likely to destroy more than carry.
	for  := 0;  < ; {
		var , ,  int
		for  <  && .oldnum[] == newIndex {
			++
		}
		if  >=  {
			break
		}
		 = 
		 = .oldnum[] - 
		++
		for  <  && .oldnum[] != newIndex && .oldnum[]- ==  {
			++
		}
		 =  - 
		if  < 3 || +min(/8, 2) < abs() {
			for  <  {
				.oldnum[] = newIndex
				++
			}
		}
	}

	// After clearing invalid hunks, try grow the rest.
	.growHunks()
}

// scrollOldhash scrolls the oldhash slice by 'n' lines between 'top' and 'bot'.
func ( *TerminalRenderer) (, ,  int) {
	if len(.oldhash) == 0 {
		return
	}

	 :=  -  + 1 - abs()
	if  > 0 {
		// Move existing hashes up
		copy(.oldhash[:], .oldhash[+:++])
		// Recalculate hashes for newly shifted-in lines
		for  := ;  > -; -- {
			.oldhash[] = hash(&.hasher, .curbuf.Line())
		}
	} else {
		// Move existing hashes down
		copy(.oldhash[-:], .oldhash[:+])
		// Recalculate hashes for newly shifted-in lines
		for  := ;  < -; ++ {
			.oldhash[] = hash(&.hasher, .curbuf.Line())
		}
	}
}

func ( *TerminalRenderer) ( *RenderBuffer) {
	var (
		    int // limits for cells to fill
		 int // limit for references
		            int
		     int
	)

	 := .Height()
	for  <  && .oldnum[] == newIndex {
		++
	}
	for ;  < ;  =  {
		var (
			    int
			 int
			             int
			           = 
			           = .oldnum[] - 
		)

		// get forward limit
		 =  + 1
		for  <  &&
			.oldnum[] != newIndex &&
			.oldnum[]- ==  {
			++
		}

		 = 
		for  <  && .oldnum[] == newIndex {
			++
		}

		 = 
		 = 
		if  >=  || .oldnum[] >=  {
			 = 
		} else {
			 = .oldnum[]
		}

		 =  - 1

		// grow back
		if  < 0 {
			 =  + (-)
		}
		for  >=  {
			if .newhash[] == .oldhash[+] ||
				.costEffective(, +, ,  < 0) {
				.oldnum[] =  + 
			} else {
				break
			}
			--
		}

		 = 
		// grow forward
		if  > 0 {
			 =  - 
		}
		for  <  {
			if .newhash[] == .oldhash[+] ||
				.costEffective(, +, ,  > 0) {
				.oldnum[] =  + 
			} else {
				break
			}
			++
		}

		 = 
		 = 
		if  > 0 {
			 += 
		}
	}
}

// costEffective returns true if the cost of moving line 'from' to line 'to' seems to be
// cost effective. 'blank' indicates whether the line 'to' would become blank.
func ( *TerminalRenderer) ( *RenderBuffer, ,  int,  bool) bool {
	if  ==  {
		return false
	}

	 := .oldnum[]
	if  == newIndex {
		 = 
	}

	// On the left side of >= is the cost before moving. On the right side --
	// cost after moving.

	// Calculate costs before moving.
	var  int
	if  {
		// Cost of updating blank line at destination.
		 = .updateCostBlank(, .Line())
	} else {
		// Cost of updating exiting line at destination.
		 = .updateCost(, .curbuf.Line(), .Line())
	}

	// Add cost of updating source line
	 += .updateCost(, .curbuf.Line(), .Line())

	// Calculate costs after moving.
	var  int
	if  ==  {
		// Source becomes blank after move
		 = .updateCostBlank(, .Line())
	} else {
		// Source gets updated from another line
		 = .updateCost(, .curbuf.Line(), .Line())
	}

	// Add cost of moving source line to destination
	 += .updateCost(, .curbuf.Line(), .Line())

	// Return true if moving is cost effective (costs less or equal)
	return  >= 
}

func ( *TerminalRenderer) ( *RenderBuffer, ,  Line) ( int) {
	var ,  int
	for  := .curbuf.Width();  > 0; , ,  = -1, +1, +1 {
		if !cellEqual(.At(), .At()) {
			++
		}
	}
	return
}

func ( *TerminalRenderer) ( *RenderBuffer,  Line) ( int) {
	// This assumes bce capability.
	 := .clearBlank()
	var  int
	for  := .curbuf.Width();  > 0; ,  = -1, +1 {
		if !cellEqual(, .At()) {
			++
		}
	}
	return
}