package parquet

// DedupeRowReader constructs a row reader which drops duplicated consecutive
// rows, according to the comparator function passed as argument.
//
// If the underlying reader produces a sequence of rows sorted by the same
// comparison predicate, the output is guaranteed to produce unique rows only.
func ( RowReader,  func(Row, Row) int) RowReader {
	return &dedupeRowReader{reader: , compare: }
}

type dedupeRowReader struct {
	reader  RowReader
	compare func(Row, Row) int
	dedupe
}

func ( *dedupeRowReader) ( []Row) (int, error) {
	for {
		,  := .reader.ReadRows()
		 = .deduplicate([:], .compare)

		if  > 0 ||  != nil {
			return , 
		}
	}
}

// DedupeRowWriter constructs a row writer which drops duplicated consecutive
// rows, according to the comparator function passed as argument.
//
// If the writer is given a sequence of rows sorted by the same comparison
// predicate, the output is guaranteed to contain unique rows only.
func ( RowWriter,  func(Row, Row) int) RowWriter {
	return &dedupeRowWriter{writer: , compare: }
}

type dedupeRowWriter struct {
	writer  RowWriter
	compare func(Row, Row) int
	dedupe
	rows []Row
}

func ( *dedupeRowWriter) ( []Row) (int, error) {
	// We need to make a copy because we cannot modify the rows slice received
	// as argument to respect the RowWriter contract.
	.rows = append(.rows[:0], ...)
	defer func() {
		for  := range .rows {
			.rows[] = Row{}
		}
	}()

	if  := .deduplicate(.rows, .compare);  > 0 {
		,  := .writer.WriteRows(.rows[:])
		if  != nil {
			return , 
		}
	}

	// Return the number of rows received instead of the number of deduplicated
	// rows actually written to the underlying writer because we have to repsect
	// the RowWriter contract.
	return len(), nil
}

type dedupe struct {
	alloc   rowAllocator
	lastRow Row
	uniq    []Row
	dupe    []Row
}

func ( *dedupe) () {
	.alloc.reset()
	.lastRow = .lastRow[:0]
}

func ( *dedupe) ( []Row,  func(Row, Row) int) int {
	defer func() {
		for  := range .uniq {
			.uniq[] = Row{}
		}
		for  := range .dupe {
			.dupe[] = Row{}
		}
		.uniq = .uniq[:0]
		.dupe = .dupe[:0]
	}()

	 := .lastRow

	for ,  := range  {
		if len() != 0 && (, ) == 0 {
			.dupe = append(.dupe, )
		} else {
			 = 
			.uniq = append(.uniq, )
		}
	}

	 = [:0]
	 = append(, .uniq...)
	 = append(, .dupe...)

	.alloc.reset()
	.alloc.capture()
	.lastRow = append(.lastRow[:0], ...)
	return len(.uniq)
}