// This file is part of the laron-crypto
//
// Copyright 2023 Ade M Ramdani
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use constant_time_eq::constant_time_eq;
use k256::ecdsa::VerifyingKey;
use k256::NonZeroScalar;
use rand::RngCore;

use crate::{
    error::{Error, Result},
    PublicKey,
};

/// Byte size of the PrivateKey
const SIZE: usize = 32;

/// Private Key
#[derive(Debug, Clone, Copy)]
pub struct PrivateKey {
    bytes: [u8; SIZE],
}

impl PartialEq for PrivateKey {
    fn eq(&self, other: &Self) -> bool {
        constant_time_eq(&self.bytes, &other.bytes)
    }
}

impl Eq for PrivateKey {}

impl PrivateKey {
    /// Create a new PrivateKey
    pub fn new() -> Self {
        let mut rng = rand::thread_rng();
        let mut bytes = [0u8; SIZE];
        rng.fill_bytes(&mut bytes);
        Self { bytes }
    }

    /// Create a new PrivateKey from bytes
    pub fn from_bytes(bytes: [u8; SIZE]) -> Self {
        Self { bytes }
    }

    /// Create a new PrivateKey from slice
    pub fn from_slice(slice: &[u8]) -> Result<Self> {
        if slice.len() != SIZE {
            Err(Error::LengthError(
                "PrivateKey size must be 32 bytes".to_string(),
            ))
        } else {
            let mut new_bytes = [0u8; SIZE];
            new_bytes.copy_from_slice(slice);
            Ok(Self::from_bytes(new_bytes))
        }
    }

    /// Create a new PrivateKey from hex string
    pub fn from_hex(hex: &str) -> Result<Self> {
        if hex.len() != SIZE * 2 {
            Err(Error::LengthError(
                "PrivateKey hex must be 64 characters".to_string(),
            ))
        } else {
            let bytes = hex::decode(hex)?;
            Self::from_slice(&bytes)
        }
    }

    /// Get the PrivateKey as bytes
    pub fn as_bytes(&self) -> [u8; SIZE] {
        self.bytes
    }

    /// Get the PrivateKey as slice
    pub fn as_slice(&self) -> &[u8] {
        &self.bytes
    }

    /// Get the PrivateKey as hex string
    pub fn as_hex(&self) -> String {
        hex::encode(self.bytes)
    }

    /// Generate public key.
    pub fn public_key(&self) -> PublicKey {
        let sk = k256::SecretKey::from_slice(&self.bytes).unwrap();
        let pk = sk.public_key();
        let vk: VerifyingKey = pk.into();
        let bytes = vk.to_encoded_point(false);
        PublicKey::from_slice(bytes.as_bytes()).unwrap()
    }

    /// Derive child key from parent key.
    pub fn derive_child(&self, other: [u8; 32]) -> Result<Self> {
        let current = k256::SecretKey::from_slice(&self.bytes).unwrap();
        let child_scalar = Option::<NonZeroScalar>::from(NonZeroScalar::from_repr(other.into()))
            .ok_or(Error::PrivateKeyError)?;
        let derived_scalar = current.to_nonzero_scalar().as_ref() + child_scalar.as_ref();
        let derived: k256::SecretKey =
            Option::<NonZeroScalar>::from(NonZeroScalar::new(derived_scalar))
                .map(Into::into)
                .ok_or(Error::PrivateKeyError)?;
        let bytes = derived.to_bytes();
        Self::from_slice(bytes.as_slice())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_private_key() {
        let key = PrivateKey::new();
        let bytes = key.as_bytes();
        assert_eq!(bytes.len(), 32);
        let slice = key.as_slice();
        assert_eq!(slice.len(), 32);
        let hex = key.as_hex();
        assert_eq!(hex.len(), 64);
        let key2 = PrivateKey::from_hex(&hex).unwrap();
        assert_eq!(key, key2);
    }
}
