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 CarDetailsForm : Form
    {

        Car car;

        public CarDetailsForm(Car car)
        {
            InitializeComponent();
            this.car = car;
            tbxMake.Text = car.Make;
            tbxModel.Text = car.Model;
            nudYear.Value = car.Year;
            tbxColor.Text = car.Color;
            nudMileage.Value = car.Mileage;
            nudPrice.Value = car.Price;
            pbxCarImage.Image = ImageManager.GetImage(car);
            lblID.Text = $"ID: {car.Id}";
        }

        private void tbxMake_TextChanged(object sender, EventArgs e)
        {
            car.Make = tbxMake.Text;
        }

        private void tbxModel_TextChanged(object sender, EventArgs e)
        {
            car.Model = tbxModel.Text;
        }

        private void nudYear_ValueChanged(object sender, EventArgs e)
        {
            car.Year = (int)nudYear.Value;
        }

        private void tbxColor_TextChanged(object sender, EventArgs e)
        {
            car.Color = tbxColor.Text;
        }

        private void nudMileage_ValueChanged(object sender, EventArgs e)
        {
            car.Mileage = (int)nudMileage.Value;
        }

        private void nudPrice_ValueChanged(object sender, EventArgs e)
        {
            car.Price = nudPrice.Value;
        }

        private async void btnSave_Click(object sender, EventArgs e)
        {
            // save car to cars.csv and close form
            //saving car... popuo
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
            var msgbox = new PleaseWait();
            msgbox.Show();
            await Task.Run(() =>
            {
                StateManager.UpdateCar(car);
                Console.WriteLine("Saved car: " + car.Id);
            });
            Console.WriteLine("Car saved. " + car.Id);
            btnSave.Enabled = true;
            btnDelete.Enabled = true;
            this.Close();
            msgbox.Close();
            


        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            //are you sure?
            var result = MessageBox.Show("Are you sure you want to delete this car?", "Delete Car", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                Console.WriteLine("Deleting car: " + car.Id);
                StateManager.RemoveCar(car);
                this.Close();
            }
        }

    }
}
