// package ope is the Order-Preserving Encryption
// 保序加密, 即保持密文的顺序. 可用于数据库.
package ope

func bytesToCoins(b []byte) []byte {
	res := make([]byte, 0, 8*len(b))
	for _, x := range b {
		for i := 0; i < 8; i++ {
			res = append(res, x&1)
			x >>= 1
		}
	}
	return res
}

// ValueRange reprents the range [start, end]
type ValueRange struct {
	start int64
	end   int64
}

func (v *ValueRange) Set(start int64, end int64) *ValueRange {
	if start > end {
		panic("not a valid value range, start must no greater then end")
	}
	v.start = start
	v.end = end
	return v
}

func (v *ValueRange) Size() int64 {
	return v.end - v.start + 1
}

func (v *ValueRange) Contains(n int64) bool {
	return n >= v.start && n <= v.end
}

// func (v *ValueRange) BitSize() int64 {
// 	n := v.Size()
// 	return int64(n.BitLen())
// }

func (v *ValueRange) Clone() *ValueRange {
	return new(ValueRange).Set(v.start, v.end)
}

// UniformRand returns a number in range uniformly
func UniformRand(M *ValueRange, coins []byte) int64 {
	start, end := M.start, M.end
	for i := 0; end > start; i++ {
		mid := (start + end) / 2
		if coins[i] == 0 {
			end = mid
		} else {
			start = mid + 1
		}
	}
	return start
}

// HyperGeometricRand returns a number x in inRange, satisfying the distribution
// Prob[X = x] = HyperGeometric(M, N, y)
func HyperGeometricRand(M, N *ValueRange, y int64, coins []byte) int64 {
	m := M.Size()
	n := N.Size()

	nsampleIndex := y - N.start + 1
	if M == N {
		return M.start + nsampleIndex - 1
	}

	inSampleNum := hypergeometric(m, n, nsampleIndex, coins)
	if inSampleNum == 0 {
		return M.start
	} else {
		return M.start + inSampleNum - 1
	}
}

type OPE struct {
}

func (o *OPE) Init(key []byte) {

}

func (o *OPE) Encrypt() {

}

func (o *OPE) Decrypts() {

}

func tapeGen(key []byte, data []byte) []byte {
	return nil

}

func sampleUniform() {

}
