use super::v221;
use crate::{
    cdr,
    json::{self, FromJson as _},
    price::{normalize_periods, Period, PeriodNormalized},
    test::{self, datetime_from_str},
};

#[test]
fn should_extract_periods() {
    const CDR_JSON: &str =
        include_str!("../../test_data/v221/real_world/step_size_energy/cdr1.json");
    const TIMEZONE: chrono_tz::Tz = chrono_tz::Tz::Europe__Amsterdam;

    test::setup();

    let (cdr_elem, warnings) =
        cdr::build(json::parse_object(CDR_JSON).unwrap(), crate::Version::V221).into_parts();

    assert!(
        warnings.is_empty(),
        "The tariff has warnings;\n{:?}",
        warnings.path_id_map()
    );
    let cdr = v221::Cdr::from_json(cdr_elem.as_element()).unwrap();
    let (cdr, warnings) = cdr.into_parts();
    assert!(
        warnings.is_empty(),
        "The CDR has warnings;\n{:?}",
        warnings.path_id_map()
    );

    let periods = cdr.charging_periods.into_iter().map(Period::from).collect();
    let periods = normalize_periods(periods, cdr.end_date_time, TIMEZONE);

    let [period_0, period_1, period_2] = periods.try_into().unwrap();

    assert_eq!(period_0.start_snapshot.local_timezone, TIMEZONE);
    assert_eq!(
        period_0.end_snapshot.local_timezone,
        period_1.start_snapshot.local_timezone
    );
    assert_eq!(
        period_1.end_snapshot.local_timezone,
        period_2.start_snapshot.local_timezone
    );
    assert_eq!(
        period_0.end_snapshot.date_time,
        period_1.start_snapshot.date_time
    );
    assert_eq!(
        period_1.end_snapshot.date_time,
        period_2.start_snapshot.date_time
    );

    {
        let PeriodNormalized { start_snapshot, .. } = period_0;
        assert_eq!(
            start_snapshot.date_time,
            datetime_from_str("2022-01-13T16:55:00")
        );
    }

    {
        let PeriodNormalized {
            start_snapshot,
            end_snapshot,
            ..
        } = period_1;
        assert_eq!(
            start_snapshot.date_time,
            datetime_from_str("2022-01-13T17:00:00")
        );
        assert_eq!(
            end_snapshot.date_time,
            datetime_from_str("2022-01-13T17:02:00")
        );
    }

    {
        let PeriodNormalized {
            start_snapshot,
            end_snapshot,
            ..
        } = period_2;
        assert_eq!(
            start_snapshot.date_time,
            datetime_from_str("2022-01-13T17:02:00")
        );
        assert_eq!(
            end_snapshot.date_time,
            datetime_from_str("2022-01-13T17:07:00")
        );
    }
}
