package dhellman

import (
	"context"
	"errors"
	"math/big"

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

type curveKeyPublic struct {
	p *tools.Point
}

func (s *curveKeyPublic) Map() json.Map {
	return json.Map{
		"p": s.p,
	}
}

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

func (s *curveKeyPublic) Attack(ctx context.Context) (curve.KeyPair, error) {
	return nil, nil
}

func (s *curveKeyPublic) attack(ctx context.Context) (*curveKeyPair, error) {
	c := s.p.Curve()
	tmp := big.NewInt(1)
	for {
		if tmp.Cmp(tools.Add64(c.P(), -1)) == 0 {
			break
		}
		if pp, err := c.G().Mul(tmp); err == nil && pp.X() != nil && pp.X().Cmp(s.p.X()) == 0 && pp.Y().Cmp(s.p.Y()) == 0 {
			pair := &curveKeyPair{
				curve: c,
				pub:   s,
				priv: &curveKeyPrivate{
					x: tmp,
				},
			}
			return pair, nil
		}
		select {
		case <-ctx.Done():
			return nil, errors.New("атака на метод диффи-хеллмана провалена: время вышло")
		default:
			tmp = tools.Add64(tmp, 1)
		}
	}
	return nil, errors.New("атака на метод диффи-хеллмана провалена: время вышло")
}