package dhellman

import (
	"math/big"

	"git.ali33.ru/fcg-xvii/curve/v2/tools"
	"git.ali33.ru/fcg-xvii/go-tools/json"
)

func randomCurveKeyPrivate(curve *tools.Curve) (priv *curveKeyPrivate, err error) {
	if err = curve.IsValidP(); err != nil {
		return
	}
	priv = &curveKeyPrivate{
		x: tools.Random(big.NewInt(1), tools.Sub64(curve.P(), 1)),
	}
	return
}

type curveKeyPrivate struct {
	x *big.Int
}

func (s *curveKeyPrivate) Map() json.Map {
	return json.Map{
		"x": s.x,
	}
}

func (s *curveKeyPrivate) MarshalJSON() ([]byte, error) {
	return s.Map().JSON(), nil
}

func (s *curveKeyPrivate) secret(pub *curveKeyPublic) (*tools.Point, error) {
	curve := pub.p.Curve()
	if err := curve.IsValidG(); err != nil {
		return nil, err
	}
	return pub.p.Mul(s.x)
}