use bevy::{
    input::{mouse::MouseWheel, ButtonInput},
    prelude::*,
    render::camera::Camera,
    window::PrimaryWindow,
};

use crate::TileOffset;

pub fn mouse_zoom(
    mut evr_scroll: EventReader<MouseWheel>,
    mut query: Query<&mut OrthographicProjection, With<Camera>>,
) {
    use bevy::input::mouse::MouseScrollUnit;
    for ev in evr_scroll.read() {
        match ev.unit {
            MouseScrollUnit::Line => {
                let scroll = ev.y / 10.0;

                for mut ortho in query.iter_mut() {
                    ortho.scale -= scroll;
                    ortho.scale = ortho.scale.clamp(0.5, 1.0);
                    dbg!(ortho.scale);
                }
            }
            MouseScrollUnit::Pixel => {}
        }
    }
}

pub fn mouse_movement(
    primary_window: Query<&Window, With<PrimaryWindow>>,
    mouse_buttons: Res<ButtonInput<MouseButton>>,
    mut query: Query<(&mut Transform, &mut TileOffset, &OrthographicProjection), With<Camera>>,
    mut last_pos: Local<Option<Vec2>>,
) {
    if !mouse_buttons.pressed(MouseButton::Middle) {
        *last_pos = None;
        return;
    }

    let Ok(window) = primary_window.get_single() else {
        return;
    };

    for (mut transform, mut offset, ortho) in query.iter_mut() {
        let current_pos = match window.cursor_position() {
            Some(c) => Vec2::new(c.x, -c.y),
            None => return,
        };
        let delta_device_pixels = current_pos - last_pos.unwrap_or(current_pos);
        *last_pos = Some(current_pos);

        let z = transform.translation.z;
        offset.translation.x -= delta_device_pixels.x * ortho.scale;
        offset.translation.y -= delta_device_pixels.y * ortho.scale;

        offset.x = (offset.translation.x / 16.0) as isize;
        offset.y = (offset.translation.y / 16.0) as isize;

        transform.translation = offset.translation % 16.0;

        transform.translation.z = z;
    }
}
