use crate::{
    datafile::datafile::DataFile,
    targeting::{
        TargetingData,
        conditions::{TargetingCondition, number_condition::NumberCondition},
        models::VisitsCPModel,
    },
};

pub(crate) struct VisitNumberTotalCondition {
    number_condition: NumberCondition<u32>,
}

impl VisitNumberTotalCondition {
    pub fn from_json(model: VisitsCPModel) -> Option<Self> {
        let number_condition = NumberCondition::new(model.visit_count, model.match_type)?;
        return Some(Self { number_condition });
    }
}

impl TargetingCondition for VisitNumberTotalCondition {
    fn check(&self, data: &TargetingData<impl DataFile>) -> Option<bool> {
        let visit_count = data.visitor_data.visitor_visits.r().get().map_or(1, |vv| vv.prev_visits().len() as u32 + 1);
        return Some(self.number_condition.check(visit_count));
    }
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, SystemTime};

    use crate::{
        data::{
            BaseData,
            visitor_visits::{Visit, VisitorVisits},
        },
        datafile::datafile_test_utils::MockDataFile,
        storage::visitor::Visitor,
        targeting::TargetingDataBuilder,
        utils::{test_utils::assert_targeting, time_utils::millis_to_time},
    };

    use rstest::rstest;

    fn new_vv(prev_visits: Vec<Visit>) -> VisitorVisits {
        return VisitorVisits::new(prev_visits.len() as u32, prev_visits, SystemTime::UNIX_EPOCH, Duration::ZERO);
    }

    fn new_visit(ts: u64) -> Visit {
        return Visit::new(millis_to_time(ts), millis_to_time(ts));
    }

    #[rstest]
    // LOWER
    #[case(None, true)]
    #[case(Some(new_vv(vec![])), true)]
    #[case(Some(new_vv(vec![new_visit(1)])), false)]
    // EXACT
    #[case(Some(new_vv(vec![new_visit(2), new_visit(1)])), true)]
    // GREATER
    #[case(Some(new_vv(vec![new_visit(3), new_visit(2), new_visit(1)])), false)]
    #[case(Some(new_vv(vec![new_visit(4), new_visit(3), new_visit(2), new_visit(1)])), true)]
    fn test_check(#[case] visitor_visits: Option<VisitorVisits>, #[case] expected: bool) {
        let datafile = MockDataFile::default();
        let visitor = Visitor::new();
        if let Some(visitor_visits) = visitor_visits {
            visitor.add_data([BaseData::VisitorVisits(visitor_visits)].into_iter(), true);
        }
        assert_targeting(
            "resources/conditions/mock_segment_visit_total.json",
            &TargetingDataBuilder::new().build(&datafile, &visitor.rdata()),
            expected,
        );
    }
}
