package fee

import (
	"git.marketally.com/tutus-one/tutus-chain/pkg/io"
	"git.marketally.com/tutus-one/tutus-chain/pkg/smartcontract/scparser"
	"git.marketally.com/tutus-one/tutus-chain/pkg/vm"
	"git.marketally.com/tutus-one/tutus-chain/pkg/vm/emit"
	"git.marketally.com/tutus-one/tutus-chain/pkg/vm/opcode"
)

// ECDSAVerifyPrice is a gas price of a single verification.
const ECDSAVerifyPrice = 1 << 15

// Calculate returns network fee for a transaction in Datoshi units.
func Calculate(base int64, script []byte) (int64, int) {
	var (
		netFee int64
		size   int
	)
	if scparser.IsSignatureContract(script) {
		size += 67 + io.GetVarSize(script)
		netFee += Opcode(base, opcode.PUSHDATA1, opcode.PUSHDATA1) + base*ECDSAVerifyPrice
	} else if m, pubs, ok := scparser.ParseMultiSigContract(script); ok {
		n := len(pubs)
		sizeInv := 66 * m
		size += io.GetVarSize(sizeInv) + sizeInv + io.GetVarSize(script)
		netFee += calculateMultisig(base, m) + calculateMultisig(base, n)
		netFee += base * ECDSAVerifyPrice * int64(n)
	} /*else {
		// We can support more contract types in the future.
	}*/
	return vm.PicoGasToDatoshi(netFee), size
}

func calculateMultisig(base int64, n int) int64 {
	result := Opcode(base, opcode.PUSHDATA1) * int64(n)
	bw := io.NewBufBinWriter()
	emit.Int(bw.BinWriter, int64(n))
	// it's a hack because coefficients of small PUSH* opcodes are equal
	result += Opcode(base, opcode.Opcode(bw.Bytes()[0]))
	return result
}
