/*  OpenTally: Open-source election vote counting
 *  Copyright © 2021 Lee Yingtong Li (RunasSudo)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use super::{Assign, Number};

use ibig::{IBig, ops::Abs};
use num_traits::{Num, One, Signed, Zero};

use std::cell::{Cell, UnsafeCell};
use std::cmp::{Ord, PartialEq, PartialOrd};
use std::ops;
use std::fmt;

thread_local! {
	static DPS: Cell<usize> = Cell::new(5);
	static FACTOR: UnsafeCell<IBig> = UnsafeCell::new(IBig::from(10).pow(5));
}

pub fn get_dps() -> usize {
	return DPS.with(|dps_cell| dps_cell.get());
}

fn get_factor<'a>() -> &'a IBig {
	FACTOR.with(|factor_cell| {
		let factor_ptr = factor_cell.get();
		// SAFETY: Safe if requirements of Fixed::set_dps met
		let factor_ref = unsafe { &*factor_ptr };
		return factor_ref;
	})
}

/// Fixed-point number
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Fixed(IBig);

impl Fixed {
	/// Set the number of decimal places to compute results to
	///
	/// SAFETY: This must be called before, and never after, any operations on [Fixed].
	pub fn set_dps(dps: usize) {
		DPS.with(|dps_cell| {
			dps_cell.set(dps);
		});
		FACTOR.with(|factor_cell| {
			let factor = IBig::from(10).pow(dps);
			let factor_ptr = factor_cell.get();
			// SAFETY: Safe if requirements above met
			unsafe {
				*factor_ptr = factor;
			}
		});
	}
}

impl Number for Fixed {
	fn new() -> Self { Self(IBig::zero()) }
	
	fn describe() -> String { format!("--numbers fixed --decimals {}", get_dps()) }
	
	fn pow_assign(&mut self, exponent: i32) {
		if exponent < 0 {
			todo!();
		}
		self.0 = self.0.pow(exponent as usize) * get_factor() / get_factor().pow(exponent as usize);
	}
	
	fn floor_mut(&mut self, dps: usize) {
		// Only do something if truncating
		if dps < get_dps() {
			let factor = IBig::from(10).pow(get_dps() - dps);
			self.0 /= &factor;
			self.0 *= factor;
		}
	}
	
	fn ceil_mut(&mut self, dps: usize) {
		// Only do something if truncating
		if dps < get_dps() {
			self.0 -= IBig::one();
			let factor = IBig::from(10).pow(get_dps() - dps);
			self.0 /= &factor;
			self.0 += IBig::one();
			self.0 *= factor;
		}
	}
	
	fn round_mut(&mut self, dps: usize) {
		// Only do something if truncating
		if dps < get_dps() {
			let mut factor = IBig::from(10).pow(get_dps() - dps);
			factor /= IBig::from(2);
			
			self.0 += factor;
			self.floor_mut(dps);
		}
	}
	
	fn parse(s: &str) -> Self {
		// Parse decimal
		if s.contains('.') {
			let (whole, decimal) = s.split_once('.').unwrap();
			let whole = match IBig::from_str_radix(whole, 10) {
				Ok(value) => value,
				Err(_) => panic!("Syntax Error"),
			} * get_factor();
			let decimal = match IBig::from_str_radix(decimal, 10) {
				Ok(value) => value,
				Err(_) => panic!("Syntax Error"),
			} * get_factor() / IBig::from(10).pow(decimal.len());
			
			if whole.is_negative() {
				return Self(whole - decimal);
			} else {
				return Self(whole + decimal);
			}
		}
		
		// Parse integer
		if let Ok(value) = Self::from_str_radix(s, 10) {
			return value;
		} else {
			panic!("Syntax Error");
		}
	}
}

#[test]
fn rounding() {
	Fixed::set_dps(5);
	
	let mut x = Fixed::parse("55.550"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
	let mut x = Fixed::parse("55.552"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
	let mut x = Fixed::parse("55.555"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
	let mut x = Fixed::parse("55.557"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
	
	let mut x = Fixed::parse("55.550"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.55"));
	let mut x = Fixed::parse("55.552"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.56"));
	let mut x = Fixed::parse("55.555"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.56"));
	let mut x = Fixed::parse("55.557"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.56"));
	
	let mut x = Fixed::parse("55.550"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.55"));
	let mut x = Fixed::parse("55.552"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.55"));
	let mut x = Fixed::parse("55.555"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.56"));
	let mut x = Fixed::parse("55.557"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.56"));
}

impl Num for Fixed {
	type FromStrRadixErr = ibig::error::ParseError;
	fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
		match IBig::from_str_radix(str, radix) {
			Ok(value) => Ok(Self(value * get_factor())),
			Err(err) => Err(err)
		}
	}
}

impl Assign for Fixed {
	fn assign(&mut self, src: Self) { self.0 = src.0 }
}

impl Assign<&Self> for Fixed {
	fn assign(&mut self, src: &Self) { self.0 = src.0.clone() }
}

#[test]
fn assign() {
	Fixed::set_dps(2);
	let a = Fixed::parse("123.45");
	let b = Fixed::parse("678.90");
	
	let mut x = a.clone(); x.assign(b.clone()); assert_eq!(x, b);
	let mut x = a.clone(); x.assign(&b); assert_eq!(x, b);
}

impl From<usize> for Fixed {
	fn from(n: usize) -> Self { Self(IBig::from(n) * get_factor()) }
}

// TODO: Fix rounding
impl fmt::Display for Fixed {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let dps = match f.precision() {
			Some(precision) => if precision < get_dps() { precision } else { get_dps() },
			None => get_dps(),
		};
		
		let mut result;
		if dps == get_dps() {
			result = self.0.clone().abs().to_string();
		} else {
			// Rounding required
			let factor = IBig::from(10).pow(get_dps() - dps - 1); // -1 to account for rounding digit
			let mut rounded = (&self.0 / factor).abs() + IBig::from(5); // Add 5 to force round-to-nearest
			rounded /= IBig::from(10); // Remove rounding digit
			result = rounded.to_string();
		}
		
		//let should_add_minus = (self.0 < IBig::zero()) && result != "0";
		let should_add_minus = self.0 < IBig::zero();
		
		// Add leading 0s
		result = format!("{0:0>1$}", result, dps + 1);
		
		// Add the decimal point
		if dps > 0 {
			result.insert(result.len() - dps, '.');
		}
		
		// Add the sign
		if should_add_minus {
			result.insert(0, '-');
		}
		
		return f.write_str(&result);
	}
}

#[test]
fn display_debug() {
	Fixed::set_dps(2);
	let x = Fixed::parse("123.4"); assert_eq!(format!("{}", x), "123.40");
	let x = Fixed::parse("123.4"); assert_eq!(format!("{:?}", x), "Fixed(12340)");
}

impl One for Fixed {
	fn one() -> Self { Self(get_factor().clone()) }
}

impl Zero for Fixed {
	fn zero() -> Self { Self::new() }
	fn is_zero(&self) -> bool { self.0.is_zero() }
}

impl ops::Neg for Fixed {
	type Output = Self;
	fn neg(self) -> Self::Output { Self(-self.0) }
}

impl ops::Add for Fixed {
	type Output = Self;
	fn add(self, rhs: Self) -> Self::Output { Self(self.0 + rhs.0) }
}

impl ops::Sub for Fixed {
	type Output = Self;
	fn sub(self, rhs: Self) -> Self::Output { Self(self.0 - rhs.0) }
}

impl ops::Mul for Fixed {
	type Output = Self;
	fn mul(self, rhs: Self) -> Self::Output { Self(self.0 * rhs.0 / get_factor()) }
}

impl ops::Div for Fixed {
	type Output = Self;
	fn div(self, rhs: Self) -> Self::Output { Self(self.0 * get_factor() / rhs.0) }
}

impl ops::Rem for Fixed {
	type Output = Self;
	fn rem(self, rhs: Self) -> Self::Output { Self(self.0 % rhs.0) }
}

#[test]
fn arith_owned_owned() {
	Fixed::set_dps(2);
	let a = Fixed::parse("123.45");
	let b = Fixed::parse("678.90");
	
	assert_eq!(a.clone() + b.clone(), Fixed::parse("802.35"));
	assert_eq!(a.clone() - b.clone(), Fixed::parse("-555.45"));
	assert_eq!(a.clone() * b.clone(), Fixed::parse("83810.20")); // = 83810.205 rounds to 83810.20
	assert_eq!(a.clone() / b.clone(), Fixed::parse("0.18"));
	assert_eq!(b.clone() % a.clone(), Fixed::parse("61.65"));
}

impl ops::Add<&Self> for Fixed {
	type Output = Self;
	fn add(self, rhs: &Self) -> Self::Output { Self(self.0 + &rhs.0) }
}

impl ops::Sub<&Self> for Fixed {
	type Output = Self;
	fn sub(self, rhs: &Self) -> Self::Output { Self(self.0 - &rhs.0) }
}

impl ops::Mul<&Self> for Fixed {
	type Output = Self;
	fn mul(self, rhs: &Self) -> Self::Output { Self(self.0 * &rhs.0 / get_factor()) }
}

impl ops::Div<&Self> for Fixed {
	type Output = Self;
	fn div(self, rhs: &Self) -> Self::Output { Self(self.0 * get_factor() / &rhs.0) }
}

impl ops::Rem<&Self> for Fixed {
	type Output = Self;
	fn rem(self, rhs: &Self) -> Self::Output { Self(self.0 % &rhs.0) }
}

#[test]
fn arith_owned_ref() {
	Fixed::set_dps(2);
	let a = Fixed::parse("123.45");
	let b = Fixed::parse("678.90");
	
	assert_eq!(a.clone() + &b, Fixed::parse("802.35"));
	assert_eq!(a.clone() - &b, Fixed::parse("-555.45"));
	assert_eq!(a.clone() * &b, Fixed::parse("83810.20"));
	assert_eq!(a.clone() / &b, Fixed::parse("0.18"));
	assert_eq!(b.clone() % &a, Fixed::parse("61.65"));
}

impl ops::AddAssign for Fixed {
	fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
}

impl ops::SubAssign for Fixed {
	fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
}

impl ops::MulAssign for Fixed {
	fn mul_assign(&mut self, rhs: Self) {
		self.0 *= rhs.0;
		self.0 /= get_factor();
	}
}

impl ops::DivAssign for Fixed {
	fn div_assign(&mut self, rhs: Self) {
		self.0 *= get_factor();
		self.0 /= rhs.0;
	}
}

impl ops::RemAssign for Fixed {
	fn rem_assign(&mut self, rhs: Self) { self.0 %= rhs.0; }
}

#[test]
fn arithassign_owned() {
	Fixed::set_dps(2);
	let a = Fixed::parse("123.45");
	let b = Fixed::parse("678.90");
	
	let mut x = a.clone(); x += b.clone(); assert_eq!(x, Fixed::parse("802.35"));
	let mut x = a.clone(); x -= b.clone(); assert_eq!(x, Fixed::parse("-555.45"));
	let mut x = a.clone(); x *= b.clone(); assert_eq!(x, Fixed::parse("83810.20"));
	let mut x = a.clone(); x /= b.clone(); assert_eq!(x, Fixed::parse("0.18"));
	let mut x = b.clone(); x %= a.clone(); assert_eq!(x, Fixed::parse("61.65"));
}

impl ops::AddAssign<&Self> for Fixed {
	fn add_assign(&mut self, rhs: &Self) { self.0 += &rhs.0; }
}

impl ops::SubAssign<&Self> for Fixed {
	fn sub_assign(&mut self, rhs: &Self) { self.0 -= &rhs.0; }
}

impl ops::MulAssign<&Self> for Fixed {
	fn mul_assign(&mut self, rhs: &Self) {
		self.0 *= &rhs.0;
		self.0 /= get_factor();
	}
}

impl ops::DivAssign<&Self> for Fixed {
	fn div_assign(&mut self, rhs: &Self) {
		self.0 *= get_factor();
		self.0 /= &rhs.0;
	}
}

impl ops::RemAssign<&Self> for Fixed {
	fn rem_assign(&mut self, rhs: &Self) { self.0 %= &rhs.0; }
}

#[test]
fn arithassign_ref() {
	Fixed::set_dps(2);
	let a = Fixed::parse("123.45");
	let b = Fixed::parse("678.90");
	
	let mut x = a.clone(); x += &b; assert_eq!(x, Fixed::parse("802.35"));
	let mut x = a.clone(); x -= &b; assert_eq!(x, Fixed::parse("-555.45"));
	let mut x = a.clone(); x *= &b; assert_eq!(x, Fixed::parse("83810.20"));
	let mut x = a.clone(); x /= &b; assert_eq!(x, Fixed::parse("0.18"));
	let mut x = b.clone(); x %= &a; assert_eq!(x, Fixed::parse("61.65"));
}

impl ops::Neg for &Fixed {
	type Output = Fixed;
	fn neg(self) -> Self::Output { Fixed(-&self.0) }
}

impl ops::Add<Self> for &Fixed {
	type Output = Fixed;
	fn add(self, rhs: Self) -> Self::Output { Fixed(&self.0 + &rhs.0) }
}

impl ops::Sub<Self> for &Fixed {
	type Output = Fixed;
	fn sub(self, rhs: Self) -> Self::Output { Fixed(&self.0 - &rhs.0) }
}

impl ops::Mul<Self> for &Fixed {
	type Output = Fixed;
	fn mul(self, rhs: Self) -> Self::Output { Fixed(&self.0 * &rhs.0 / get_factor()) }
}

impl ops::Div<Self> for &Fixed {
	type Output = Fixed;
	fn div(self, rhs: Self) -> Self::Output { Fixed(&self.0 * get_factor() / &rhs.0) }
}

impl ops::Rem<Self> for &Fixed {
	type Output = Fixed;
	fn rem(self, rhs: Self) -> Self::Output { Fixed(&self.0 % &rhs.0) }
}

#[test]
fn arith_ref_ref() {
	Fixed::set_dps(2);
	let a = Fixed::parse("123.45");
	let b = Fixed::parse("678.90");
	
	assert_eq!(&a + &b, Fixed::parse("802.35"));
	assert_eq!(&a - &b, Fixed::parse("-555.45"));
	assert_eq!(&a * &b, Fixed::parse("83810.20"));
	assert_eq!(&a / &b, Fixed::parse("0.18"));
	assert_eq!(&b % &a, Fixed::parse("61.65"));
}

/*
impl ops::Add<&&Rational> for &Rational {
	
}

impl ops::Sub<&&Rational> for &Rational {
	
}

impl ops::Mul<&&Rational> for &Rational {
	
}

impl ops::Div<&&Rational> for &Rational {
	
}

impl ops::Rem<&&Rational> for &Rational {
	
}
*/
