package dkgc

import (
	"crypto/rand"
	"io"
	"math/big"

	"xdx.jelly/xgcl/sm/sm9"
)

type DoubleKGC struct {
	ks         sm9.MastSignPrivateKey
	commonPubs sm9.MastSignPublicKey
}

func (dk *DoubleKGC) GenerateMastKey() {

}

var alpha = big.NewInt(2)
var alphaInv = new(big.Int).ModInverse(alpha, sm9.Order())

func ComputeHHat(id []byte) (*big.Int, *big.Int, bool) {
	h1 := sm9.H1(id, []byte{0x01})
	hh := new(big.Int).ModSqrt(h1, sm9.Order())
	if hh == nil {
		hh = new(big.Int).Lsh(h1, 1)
		hh.ModSqrt(hh, sm9.Order())
		return h1, hh, false
	}
	return h1, hh, true
}

func UserRandom0(reader io.Reader, basePoint *sm9.G1) (*big.Int, *sm9.G1, error) {
	r, err := rand.Int(reader, sm9.Order())
	if err != nil || r.Sign() == 0 {
		return nil, nil, err
	}
	R := &sm9.G1{}
	R.ScalarMult(basePoint, r)
	return r, R, nil
}

func KGC1ComputeData(reader io.Reader, R *sm9.G1, ks *sm9.MastSignPrivateKey, hh *big.Int) (*big.Int, *sm9.G1, error) {
	r, err := rand.Int(reader, sm9.Order())
	if err != nil {
		return nil, nil, err
	}

	t1 := new(big.Int).Add(hh, &ks.Int)
	t1.Mod(t1, sm9.Order())
	if t1.Sign() == 0 {
		panic("Got zero of t1")
	}
	t1.ModInverse(t1, sm9.Order())
	t1.Mul(t1, r)
	t1.Mod(t1, sm9.Order())

	r.ModInverse(r, sm9.Order())
	T1 := new(sm9.G1).ScalarMult(R, r)
	return t1, T1, nil
}

func KGC2ComputeData(T1 *sm9.G1, ks *sm9.MastSignPrivateKey, hh *big.Int) (*sm9.G1, error) {
	t2 := new(big.Int).Add(hh, &ks.Int)
	t2.ModInverse(t2, sm9.Order())
	T2 := new(sm9.G1).ScalarMult(T1, t2)
	return T2, nil
}

func UserComputeSignKey(id []byte, t1 *big.Int, T2 *sm9.G1, r *big.Int, pubs1, pubs2, pubs *sm9.MastSignPublicKey, basePoint *sm9.G1) (*sm9.UserSignKey, *sm9.MastSignPublicKey, error) {
	h1, hh, isSquare := ComputeHHat(id)
	rInv := new(big.Int).ModInverse(r, sm9.Order())
	if isSquare {
		// h1 is square
		d := new(big.Int).Mul(h1, t1)
		d.Mul(d, rInv)
		d.Mod(d, sm9.Order())
		ds := new(sm9.G1).ScalarMult(T2, d)
		ds.Neg(ds)
		// ds.Add(ds, sm9.G1Generator())
		ds.Add(ds, basePoint)

		g := new(sm9.G2).Add(&pubs1.G2, &pubs2.G2)
		g.ScalarMult(g, hh)
		g.Add(g, &pubs.G2)
		return &sm9.UserSignKey{
				G1: *ds,
			}, &sm9.MastSignPublicKey{
				G2: *g,
			}, nil
	} else {
		d := new(big.Int).Mul(h1, t1)
		d.Mul(d, rInv)
		d.Mul(d, alpha)
		d.Mod(d, sm9.Order())

		ds := new(sm9.G1).ScalarMult(T2, d)
		ds.Neg(ds)
		// ds.Add(ds, sm9.G1Generator())
		ds.Add(ds, basePoint)

		g := new(sm9.G2).Add(&pubs1.G2, &pubs2.G2)
		g.ScalarMult(g, hh)
		g.ScalarMult(g, alphaInv)
		g.Add(g, new(sm9.G2).ScalarMult(&pubs.G2, alphaInv))
		return &sm9.UserSignKey{
				G1: *ds,
			}, &sm9.MastSignPublicKey{
				G2: *g,
			}, nil
	}
}
