using System.Linq;
using System.Windows.Input;
using devDept.Eyeshot;
using devDept.Eyeshot.Control;
using devDept.Eyeshot.Entities;
using WpfEngineeringSketch.Models.Scene;
using WpfEngineeringSketch.Rendering;
using WpfEngineeringSketch.ViewModels;

namespace WpfEngineeringSketch.Tools3D
{
    public class PathTool3D : I3DTool
    {
        public string Name => "Path Builder";

        public void Activate(MainViewModel vm) 
        {
            // Optional: visual cue?
        }

        public void Deactivate(MainViewModel vm) 
        {
            // clear selection? Or keep it? keeping it allows switching tools while keeping selection.
        }

        public void OnMouseDown(MainViewModel vm, Design design, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
            {
                var point = e.GetPosition(design);
                var item = design.GetItemUnderMouseCursor(new System.Drawing.Point((int)point.X, (int)point.Y));
                
                if (item != null && item.Item is Entity entity)
                {
                    var obj = SceneBinder.GetSceneObjectFromEntity(entity);
                    if (obj != null && obj.Type == BlockType.GridLine)
                    {
                        // Toggle Selection
                        obj.IsSelected = !obj.IsSelected;
                        
                        // Eyeshot visual update is handled via SceneBinder PropertyChanged or we force it here
                        // SceneBinder handles PropertyChanged -> entity.Selected = value
                        
                        if (obj.IsSelected)
                        {
                            if (!vm.SelectedObjects.Contains(obj))
                            {
                                vm.SelectedObjects.Add(obj);
                            }
                        }
                        else
                        {
                            vm.SelectedObjects.Remove(obj);
                        }
                        
                        // Update main selected object to latest
                        vm.SelectedObject = obj.IsSelected ? obj : vm.SelectedObjects.LastOrDefault();
                        
                        return; // Hit one, stop.
                    }
                }
            }
        }

        public void OnMouseMove(MainViewModel vm, Design design, MouseEventArgs e) { }

        public void OnMouseUp(MainViewModel vm, Design design, MouseButtonEventArgs e) { }
    }
}


