use yew::prelude::*;
use yewdux::prelude::*;

use crate::components::states::CurrentTransfer;
use plate_tool_lib::transfer_region::Region;

// Color Palette for the Source Plates, can be changed here

use super::super::transfer_menu::RegionDisplay;

use super::plate_data::*;

pub fn mouse_callback(
    m_start_handle: MStartHandle,
    m_end_handle: MEndHandle,
    m_stat_handle: MStatHandle,
) -> Callback<(u8, u8, MouseEventType)> {
    Callback::from(move |(i, j, t)| match t {
        MouseEventType::Mousedown => {
            m_start_handle.set(Some((i, j)));
            m_end_handle.set(Some((i, j)));
            m_stat_handle.set(true);
        }
        MouseEventType::Mouseenter => {
            if *m_stat_handle {
                m_end_handle.set(Some((i, j)));
            }
        }
    })
}

pub fn mouseup_callback(
    m_start_handle: MStartHandle,
    m_end_handle: MEndHandle,
    m_stat_handle: MStatHandle,
    ct_dispatch: Dispatch<CurrentTransfer>,
) -> Callback<MouseEvent> {
    Callback::from(move |_: MouseEvent| {
        m_stat_handle.set(false);
        if let Some(ul) = *m_start_handle {
            if let Some(br) = *m_end_handle {
                if let Ok(rd) = RegionDisplay::try_from((ul.0, ul.1, br.0, br.1)) {
                    ct_dispatch.reduce_mut(|state| {
                        state.transfer.transfer_region.source_region = Region::from(&rd);
                    });
                }
            }
        }
    })
}
