/*
Copyright (c) 2022 Peter Hristozov / Петър Христозов

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

//! Calendar date, Julian Date, Epoch.

/// Epoch for MJD.
pub const MJD0: f64 = 2400000.5;
/// Day in tropical year.
pub const DTROPYEAR: f64 = 365.242198781;
/// Days in Julian year.
pub const DJYEAR: f64 = 365.25;
/// Days in Julian century.
pub const DJCENT: f64 = 36525.0;
/// Days per Julian millennium {@value}
pub const DJMILL: f64 = 365250.0;
/// Seconds per day.
pub const SECDAY: f64 = 86400.0;
/// Milliseconds per day.
pub const MSECINDAY: f64 = 86400000.0;
/// Julian epoch J2000, modified Julian date of 2000 JAN 01 12:00:00 (2000 JAN 1.5).
pub const J2000: f64 = 51544.5;
/// Julian epoch J1950, modified Julian date of 1950 JAN 01 00:00:00 (1950 JAN 1.0).
pub const J1950: f64 = 33282.0;
/// Julian epoch J1900, modified Julian date of 1899 DEC 31 12:00:00 (1900 JAN 0.5).
pub const J1900: f64 = 15019.5;
/// Modified julian date corresponding to Besselian epoch 1950.0.
pub const B1950: f64 = 33281.92345905;
/// Modified julian date corresponding to Besselian epoch 1900.0.
pub const B1900: f64 = 15019.81352;

/// Structure represents a date with year, month,
/// day of a month, hours, minutes, seconds and milliseconds.
#[derive(Debug)]
pub struct Adate {
    /// Year
    pub year: i16,
    /// Month
    pub month: u8,
    /// Day in month
    pub day: u8,
    /// Hour
    pub hour: u8,
    /// Minutes
    pub min: u8,
    /// Seconds
    pub sec: u8,
    /// Milliseconds as integer
    pub msec: u16,
}
impl Adate {
    /// Gregorian Calendar to Modified Julian Date.
    /// # Arguments
    /// # Returns
    /// Modified Julian Date after -4799 1 Jan.
    /// # References
    /// Explanatory Supplement to the Astronomical Almanac,
    /// P. Kenneth Seidelmann (ed), University Science Books (1992), (p604)
    pub fn mjd(&self) -> f64 {
        if (self.year >= -4799) || (self.month >= 1) || (self.month <= 12) {
            let my: i32 = (self.month as i32 - 14) / 12;
            let iypmy: i32 = self.year as i32 + my;
            ((1461 * (iypmy + 4800)) / 4 + (367 * (self.month as i32 - 2 - 12 * my)) / 12
                - (3 * ((iypmy + 4900) / 100)) / 4
                + self.day as i32
                - 2432076) as f64
                + self.dayfrac()
        } else {
            f64::NAN
        }
    }

    /// Fraction of day from hour, minutes, seconds and milliseconds.
    /// # Arguments
    /// # Returns
    /// fraction of day
    pub fn dayfrac(&self) -> f64 {
        (self.msec as f64
            + (self.sec as f64 + (self.min as f64 + self.hour as f64 * 60.0) * 60.0) * 1000.0)
            / MSECINDAY
    }

    /// Day of year in Gregorian calendar.
    /// # Arguments
    /// # Returns
    /// day of year as integer
    pub fn day_of_year(&self) -> i16 {
        if is_leep_year(self.year) {
            (275 * self.month as i16 / 9) - ((self.month as i16 + 9) / 12) + self.day as i16 - 30
        } else {
            (275 * self.month as i16 / 9) - 2 * ((self.month as i16 + 9) / 12) + self.day as i16
                - 30
        }
    }

    //TODO day_of_week
}

/// Modified Julian Date to Gregorian year, month, day, and fractions of a day.
/// # Arguments
/// * `mjd` Modified Julian Date
/// # Returns
/// Year, month, day, hours, minites, seconds and milliseconda as Adate.
pub fn mjd_adate(mjd: f64) -> Adate {
    if (mjd >= -2468570.0) || (mjd < 997599999.5) {
        let msmjd = (mjd * MSECINDAY).round() as i64;
        let mut msdf = msmjd % 86400000i64;
        let mut lmjd = msmjd / 86400000i64;
        if msmjd >= 0 {
            lmjd += 1i64;
        } else {
            msdf += 86400000i64;
        }

        let mut l = lmjd + 68569i64 + 2400000i64;
        let n = (4i64 * l) / 146097i64;
        l -= (146097i64 * n + 3i64) / 4i64;
        let i = (4000i64 * (l + 1i64)) / 1461001i64;
        l -= (1461i64 * i) / 4i64 - 31i64;
        let k = (80i64 * l) / 2447i64;
        let dy = (l - (2447i64 * k) / 80i64) as u8;
        l = k / 11i64;
        let mh = (k + 2i64 - 12i64 * l) as u8;
        let yr = (100i64 * (n - 49i64) + i + l) as i16;

        let hr = (msdf / 3600000i64) as u8;
        msdf = msdf % 3600000i64;
        let mn = (msdf / 60000i64) as u8;
        msdf = msdf % 60000i64;
        let sc = (msdf / 1000i64) as u8;
        let ms = (msdf % 1000i64) as u16;
        Adate {
            year: yr,
            month: mh,
            day: dy,
            hour: hr,
            min: mn,
            sec: sc,
            msec: ms,
        }
    } else {
        Adate {
            year: i16::MAX,
            month: u8::MAX,
            day: u8::MAX,
            hour: u8::MAX,
            min: u8::MAX,
            sec: u8::MAX,
            msec: u16::MAX,
        }
    }
}

/// Modified Julian Date to Julian Date.
/// # Arguments
/// * `mjd` Modified Julian Date
/// # Returns
/// Julian Date
pub fn mjd_jd(mjd: f64) -> f64 {
    mjd + MJD0
}

/// Julian Date to Modified Julian Date.
/// # Arguments
/// * `jd` Julian Date
/// # Returns
/// Modified Julian Date
pub fn jd_mjd(jd: f64) -> f64 {
    jd - MJD0
}

/// Modified Julian Date to Julian Epoch.
/// # Arguments
/// * `mjd` Modified Julian Date
/// # Returns
/// Julian Epoch
/// # References
/// Lieske, J.H., 1979. Astron.Astrophys., 73, 282.
pub fn mjd_jep(mjd: f64) -> f64 {
    2000.0 + (mjd - J2000) / DJYEAR
}

/// Julian Epoch to Modified Julian Date.
/// # Arguments
/// * `jep` Julian Epoch
/// # Returns
/// Modified Julian Date
/// # References
/// Lieske, J.H., 1979. Astron.Astrophys., 73, 282.
pub fn jep_mjd(jep: f64) -> f64 {
    J2000 + (jep - 2000.0) * DJYEAR
}

/// Modified Julian Date to Besselian Epoch.
/// # Arguments
/// * `mjd` Modified Julian Date
/// # Returns
/// Besselian Epoch
/// # References
/// Lieske, J.H., 1979. Astron.Astrophys., 73, 282.
pub fn mjd_bep(mjd: f64) -> f64 {
    1900.0 + (mjd - B1900) / DTROPYEAR
}

/// Besselian Epoch to Modified Julian Date.
/// # Arguments
/// * `bep` Besselian Epoch
/// # Returns
/// Modified Julian Date
/// # References
/// Lieske, J.H., 1979. Astron.Astrophys., 73, 282.
pub fn bep_mjd(bep: f64) -> f64 {
    B1900 + (bep - 1900.0) * DTROPYEAR
}

/// Day fraction from Modified Julian Date.
/// # Arguments
/// * `mjd` Modified Julian Date
/// # Returns
/// fraction of day
pub fn mjd_dayfrac(mjd: f64) -> f64 {
    if mjd >= 0.0 {
        mjd % 1.0
    } else {
        mjd % 1.0 + 1.0
    }
}

/// Checks if a year is a leap year in Gregorian calendar.
/// # Arguments
/// * `year` Year as integer
/// # Returns
/// `true` if year is leap year, else `false`
pub fn is_leep_year(year: i16) -> bool {
    if year % 100 == 0 {
        year % 400 == 0
    } else {
        year % 4 == 0
    }
}
