using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarManagerV2
{
    internal class StateManager
    {

        static List<Car> cars = new List<Car>();

        public static Car GetCarById(int id)
        {
            cars = SafeManager.ReadCars("cars.csv");
            return cars.FirstOrDefault(c => c.Id == id);
        }

        public static List<Car> Cars { get { return cars; } set { cars = value; } }

        public static void AddCar(Car car)
        {
            cars = SafeManager.ReadCars("cars.csv");
            cars.Add(car);
            SafeManager.SaveCars("cars.csv", cars);
        }

        public static void RemoveCar(Car car)
        {
            cars = SafeManager.ReadCars("cars.csv");
            Car existingCar = GetCarById(car.Id);
            if (existingCar == null) return;
            cars.Remove(existingCar);
            SafeManager.SaveCars("cars.csv", cars);
        }

        public static void UpdateCar(Car car)
        {
            Car existingCar = GetCarById(car.Id);
            if (existingCar != null)
            {
                int index = cars.IndexOf(existingCar);
                cars[index] = car;
                Console.WriteLine("Updated car: " + existingCar.Id);
                SafeManager.SaveCars("cars.csv", cars);
            }
        }

        public static Car CreateCar(string make, string model, int year, string color, int mileage, decimal price)
        {
            cars = SafeManager.ReadCars("cars.csv");
            int newId = cars.Count > 0 ? cars.Max(c => c.Id) + 1 : 1;
            Car newCar = new Car(newId, make, model, year, color, mileage, price);
            AddCar(newCar);
            return newCar;
        }
    }
}
