using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CarManagerV3
{
    public partial class CarCard : UserControl
    {
        public Car Car;

        public string CarName
        {
            get { return lblCarName.Text; }
            set { lblCarName.Text = value; }
        }
        public string CarDetails
        {
            get { return lblCarDetails.Text; }
            set { lblCarDetails.Text = value; }
        }

        public Image CarImage
        {
            get { return pbxCar.Image; }
            set { pbxCar.Image = value; }
        }

        public CarCard()
        {
            InitializeComponent();
            this.Cursor = Cursors.Hand;

            foreach (Control ctrl in this.Controls)
            {
                ctrl.MouseClick += ForwardClick;
                foreach (Control inner in ctrl.Controls)
                {
                    inner.MouseClick += ForwardClick;
                }
            }

            this.MouseClick += (s, e) => this.OnCardClicked(s, e);
        }

        public async void LoadImage()
        {
            this.CarImage = pbxCar.InitialImage; // Set to loading image
            await Task.Run(() =>
            {
                Image img = ImageManager.GetImage(this.Car);
                if (img != null)
                {
                    this.CarImage = img;
                }
                else
                {
                    this.CarImage = pbxCar.ErrorImage; // Set to error image if loading fails
                }
            });
        }

        private void ForwardClick(object sender, MouseEventArgs e)
        {
            // Raise your CardClicked event no matter what got clicked
            if (e.Button == MouseButtons.Right) return;

            Console.WriteLine($"Forwarding click from {sender.GetType().Name}");
            CardClicked?.Invoke(this, EventArgs.Empty);
        }

        public event EventHandler CardClicked;
        private void OnCardClicked(object sender, MouseEventArgs e)
        {
            Console.WriteLine($"Card clicked at {e.Location} with button {e.Button}");
            if (e.Button == MouseButtons.Right) return;
            Console.WriteLine($"Card clicked: {this.CarName}");
            
            if (this.CardClicked != null)
            {
                this.CardClicked(this, EventArgs.Empty);
            }
        }

        public void ClearCardClickedHandlers()
        {
            if (this.CardClicked != null)
            {
                foreach (Delegate d in this.CardClicked.GetInvocationList())
                {
                    this.CardClicked -= (EventHandler)d;
                }
            }
        }
    }
}
