#include "../crypto_ec/crypto_EccP256Math.h"

#pragma once

using namespace nn::crypto0;
using namespace nn::crypto0::detail;

namespace ECQV
{
class KeyPair
{
public:
    static void GenerateKeyPair(Random&            randomGenerator,
                                p256_ec_parameter* pEcParams,
                                bigint_digit*      pPrivateKey,
                                p256_point*        pPublicKey,
                                bool               generateMinimumY = false)
    {
        // Generate random number d in the interval [1, n - 1]
        // n = order of curve.
        // TODO: alg_p256_generate_private_key(...) may be more suited for this?
        bigint_digit d[ECC_P256_BIGINT_DIGITS];
        randomGenerator.RandomBits(d);

        bigint_mod(pPrivateKey,
                   d,
                   ECC_P256_BIGINT_DIGITS,
                   pEcParams->point_order,
                   ECC_P256_BIGINT_DIGITS);

        // Avoid cases when m_privateKey is zero
        if (bigint_iszero(pPrivateKey, ECC_P256_BIGINT_DIGITS))
        {
            bigint_digit one[ECC_P256_BIGINT_DIGITS] = {1, 0, 0, 0};

            bigint_copy(pPrivateKey, one, ECC_P256_BIGINT_DIGITS);
        }

        // Public key: Q = dG
        // Q: public key, G: generator point
        p256_mul(pPublicKey,
                 pPrivateKey,
                 ECC_P256_BIGINT_DIGITS,
                 &pEcParams->par_point,
                 &pEcParams->par_curve);
        NERD_ASSERT(p256_validate(pPublicKey, &pEcParams->par_curve));

        // Select y on the curve so it always the min(y1, y2) of the y2 = C(X) equation
        // https://tools.ietf.org/html/draft-jivsov-ecc-compact-05
        // 4.2.2.  The deterministic key generation algorithm
        if (generateMinimumY)
        {
            // y = min(y,p-y)
            bigint_digit pMinusY[ECC_P256_BIGINT_DIGITS];
            bigint_sub_mod(
                pMinusY, pEcParams->p, pPublicKey->y, pEcParams->p, ECC_P256_BIGINT_DIGITS);

            if (bigint_cmp(pMinusY, pPublicKey->y, ECC_P256_BIGINT_DIGITS) == -1)
            {
                bigint_sub_mod(pPrivateKey,
                               pEcParams->point_order,
                               pPrivateKey,
                               pEcParams->point_order,
                               ECC_P256_BIGINT_DIGITS);
                bigint_copy(pPublicKey->y, pMinusY, ECC_P256_BIGINT_DIGITS);
            }

            NERD_ASSERT(p256_validate(pPublicKey, &pEcParams->par_curve));
        }
    }
};
}