use crate::components::camera::CameraComponent;
use crate::components::FollowComponent;
use crate::render::snow::SnowLayer;
use crate::utility::transform::Transform;
use crate::world::Storage;

pub fn snow_system(
    cameras: &Storage<CameraComponent>,
    transforms: &Storage<Transform>,
    player_tags: &Storage<()>,
    follows: &Storage<FollowComponent>,
    snow_layer: &mut Option<SnowLayer>,
)
{
    let camera_pos = cameras
        .components
        .iter()
        .find(|(_, cam)| cam.is_active)
        .and_then(|(e, _)| transforms.get(*e))
        .map(|t| t.position)
        .unwrap_or(glam::Vec3::ZERO);

    let player_pos = player_tags
        .all()
        .first()
        .and_then(|e| transforms.get(*e))
        .map(|t| t.position)
        .unwrap_or(glam::Vec3::ZERO);

    let is_following = cameras
        .components
        .iter()
        .find(|(_, cam)| cam.is_active)
        .map(|(e, _)| follows.get(*e).is_some())
        .unwrap_or(false);

    if let Some(ref mut snow_layer) = snow_layer
    {
        if is_following
        {
            snow_layer.deform_at_position(player_pos, 1.5, 10.0);
        }
        snow_layer.update(camera_pos);
    }
}
