use std::convert::Infallible;

// https://github.com/imneme/pcg-c
use rand::{SeedableRng, TryRng, rand_core::utils::fill_bytes_via_next_word};

#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct Pcg64Si {
    state: u64,
}

impl TryRng for Pcg64Si {
    type Error = Infallible;

    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
        Ok(self.try_next_u64()? as u32)
    }

    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
        let old_state = self.state;
        self.state = self
            .state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);

        let word =
            ((old_state >> ((old_state >> 59) + 5)) ^ old_state).wrapping_mul(12605985483714917081);
        Ok((word >> 43) ^ word)
    }

    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
        fill_bytes_via_next_word(dest, || self.try_next_u64())
    }
}

impl SeedableRng for Pcg64Si {
    type Seed = [u8; 8];

    fn from_seed(seed: Self::Seed) -> Pcg64Si {
        Pcg64Si {
            state: u64::from_le_bytes(seed),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::Rng;
    use std::collections::HashSet;

    // For a given seed the RNG is deterministic
    // thus we can perform some basic tests consistently
    #[test]
    fn test_rng_next() {
        let mut rng = Pcg64Si::from_seed([1, 2, 3, 4, 5, 6, 7, 8]);
        let mut values_set: HashSet<u32> = HashSet::new();
        // Generate 1000 values modulus 100 (so each value is between 0 and 99)
        for _ in 0..1000 {
            values_set.insert(rng.next_u32() % 100);
        }
        // Expect to generate every number between 0 and 99 (the generated values are somewhat evenly distributed)
        assert_eq!(values_set.len(), 100);
    }

    #[test]
    fn test_rng_from_seed() {
        // Different seeds should result in a different RNG state
        let rng1 = Pcg64Si::from_seed([1, 2, 3, 4, 5, 6, 7, 8]);
        let rng2 = Pcg64Si::from_seed([1, 2, 3, 4, 5, 6, 7, 7]);
        assert_ne!(rng1.state, rng2.state);
    }

    #[test]
    fn test_rng_fill_bytes() {
        // This uses the next_u64/u32 functions underneath, so don't need to test the pseudo randomness again
        let mut array: [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0];
        let mut rng = Pcg64Si::from_seed([1, 2, 3, 4, 5, 6, 7, 8]);
        rng.fill_bytes(&mut array);
        assert_ne!(array, [0, 0, 0, 0, 0, 0, 0, 0]);
    }
}
