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 CarManagerV2
{
    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.Click += ForwardClick;
                foreach (Control inner in ctrl.Controls) // In case you have nested controls
                    inner.Click += ForwardClick;
            }

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

        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;
                }
            });
        }

        private void ForwardClick(object sender, EventArgs e)
        {
            // Raise your CardClicked event no matter what got clicked
            CardClicked?.Invoke(this, EventArgs.Empty);
        }

        public event EventHandler CardClicked;
        private void OnCardClicked()
        {
            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;
                }
            }
        }
    }
}
