use crate::{
    data::DeviceKind,
    datafile::datafile::DataFile,
    targeting::{conditions::TargetingCondition, models::DeviceTypeCPModel, TargetingData},
};

pub(crate) struct DeviceCondition {
    device_kind: DeviceKind,
}

impl DeviceCondition {
    pub fn from_json(model: DeviceTypeCPModel) -> Option<Self> {
        let device_kind = DeviceKind::from_str(&model.device)?;
        return Some(Self { device_kind });
    }
}

impl TargetingCondition for DeviceCondition {
    fn check(&self, data: &TargetingData<impl DataFile>) -> Option<bool> {
        let device = data.visitor_data.device.r().get()?;
        return Some(device.kind == self.device_kind);
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        data::{BaseData, Device},
        datafile::datafile_test_utils::MockDataFile,
        storage::visitor::Visitor,
        targeting::TargetingDataBuilder,
        utils::test_utils::assert_targeting,
    };

    use super::*;
    use rstest::rstest;

    #[rstest]
    #[case(1, None, false)]
    #[case(1, Some(DeviceKind::Desktop), true)]
    #[case(1, Some(DeviceKind::Phone), true)]
    #[case(1, Some(DeviceKind::Tablet), true)]
    #[case(2, Some(DeviceKind::Desktop), true)]
    #[case(2, Some(DeviceKind::Phone), false)]
    #[case(2, Some(DeviceKind::Tablet), false)]
    fn test_check(#[case] file_index: i32, #[case] device_kind: Option<DeviceKind>, #[case] expected: bool) {
        let datafile = MockDataFile::default();
        let visitor = Visitor::new();
        if let Some(device_kind) = device_kind {
            visitor.add_data([BaseData::Device(Device::new(device_kind))].into_iter(), true);
        }
        assert_targeting(
            &format!("resources/conditions/mock_segment_device{file_index}.json"),
            &TargetingDataBuilder::new().build(&datafile, &visitor.rdata()),
            expected,
        );
    }
}
