package sdk

import (
	"crypto/elliptic"
	"encoding/binary"
	"math/big"
	"voucher/internal/pkg/cmb/sm2/util"
)

// CmbLifeSdk 招商银行生活服务
type CmbLifeSdk struct {
	BaseSdk
}

func NewCmbLifeSdk() SDK {
	return &CmbLifeSdk{}
}

func (c *CmbLifeSdk) Kdf(cur elliptic.Curve, x *big.Int, y *big.Int, c2 []byte) error {
	bufSize := 4
	digest := util.New()
	if bufSize < digest.Size() {
		bufSize = digest.Size()
	}
	buf := make([]byte, bufSize)

	encDataLen := len(c2)
	c1xBytes := util.BigIntToByte(x)
	c1yBytes := util.BigIntToByte(y)
	off := 0
	ct := uint32(0)
	for off < encDataLen {
		digest.Reset()
		digest.Write(c1xBytes)
		digest.Write(c1yBytes)
		ct++
		binary.BigEndian.PutUint32(buf, ct)
		digest.Write(buf[:4])
		tmp := digest.Sum(nil)
		copy(buf[:bufSize], tmp[:bufSize])

		xorLen := encDataLen - off
		if xorLen > digest.Size() {
			xorLen = digest.Size()
		}
		xor(c2[off:], buf, xorLen)
		off += xorLen
	}
	return nil
}

func xor(data []byte, kdfOut []byte, dRemaining int) {
	for i := 0; i < dRemaining; i++ {
		data[i] ^= kdfOut[i]
	}
}
