// Copyright (C) 2022 Marius Schellenberger

package chunk

import (
	"golang.org/x/exp/slices"
)

type Chunk [2]int64

type Chunks []Chunk

func (Chunks) Less(i, j Chunk) bool { return i[0] < j[0] }

func (cs Chunks) Exists(off int64, n int, size int64) bool {
	end := off + int64(n)
	if end > size {
		end = size
	}
	for _, c := range cs {
		if c[0] <= off && c[1] > off && c[1] >= end {
			return true
		}
	}
	return false
}

func (cs *Chunks) Add(off int64, n int) {
	*cs = append(*cs, Chunk{off, off + int64(n)})
	cs.merge()
}

func (cs Chunks) Size() (sum int64) {
	for _, c := range cs {
		sum += (c[1] - c[0])
	}
	return
}

func (cs *Chunks) merge() {
	c := *cs
	if len(c) < 2 {
		return
	}
	slices.SortFunc(c, c.Less)
	for i := 0; i < len(c); i++ {
		if i+1 == len(c) {
			break
		}
		if c[i][1] >= c[i+1][0] {
			if c[i+1][1] > c[i][1] {
				c[i][1] = c[i+1][1]
			}
			c = slices.Delete(c, i+1, i+2)
			i--
		}
	}
	*cs = c
}
