using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace CarManagerV3
{
    /// <summary>
    /// Handles safe reading and writing of car data to files.
    /// </summary>
    internal class SafeManager
    {
        /// <summary>
        /// The path of the txt file that contains recently opened file paths.
        /// </summary>
        private static readonly string recentPathsFile = "recent_paths.txt";

        /// <summary>
        /// Initializes a file at a specified path if it does not already exist.
        /// </summary>
        /// <param name="path">The path.</param>
        public static void InitializeFile(string path)
        {
            try
            {
                if (!File.Exists(@path))
                {
                    using (StreamWriter writer = new StreamWriter(@path))
                    {
                        // Create the file, empty
                        writer.WriteLine();
                        writer.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Error initializing file: {ex.Message}");
            }
        }

        /// <summary>
        /// Reads cars from a specified file path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>
        /// A <see cref="List{Car}"/> containing the cars read from the file.
        /// </returns>
        public static List<Car> ReadCars(string path)
        {
            List<Car> cars = new List<Car>();
            List<string> failedLines = new List<string>();
            try
            {
                using (StreamReader reader = new StreamReader(@path))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        // Process the line
                        if (line == "") continue;
                        Car tmp = Car.FromCsvString(line);
                        if (tmp == null)
                        {
                            failedLines.Add(line);
                            continue;
                        } 
                        cars.Add(tmp);
                    }
                    reader.Close();
                }
            } catch (Exception ex)
            {
                Console.Error.WriteLine($"Error reading cars from file: {ex.Message}");
            }
            if (failedLines.Count > 0)
            {
                Console.Error.WriteLine($"Warning: {failedLines.Count} lines could not be parsed and were skipped.");
                foreach (string failedLine in failedLines)
                {
                    Console.Error.WriteLine($"Failed line: {failedLine}");
                }
                MessageBox.Show($"Warning: {failedLines.Count} lines in the file could not be parsed and were skipped. Check the console for details.", "Parsing Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return cars;
        }

        /// <summary>
        /// Saves the cars to a specified file path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="cars">A <see cref="List{Car}"/> containing all cars to save.</param>
        public static void SaveCars(string path, List<Car> cars)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(@path))
                {
                    foreach (Car car in cars)
                    {
                        writer.WriteLine(car.ToCsvString());
                    }
                    writer.Close();
                }
            } catch (Exception ex)
            {
                Console.Error.WriteLine($"Error saving cars to file: {ex.Message}");
                MessageBox.Show($"Error saving cars to file: {ex.Message}", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Adds a file path to the recent paths list.
        /// If a path is already in the list, it is moved to the top.
        /// Otherwise, it is added to the top.
        /// Keeps only the 5 most recent paths.
        /// </summary>
        /// <param name="path">The path.</param>
        public static void AddRecentPath(string path)
        {
            List<string> paths = new List<string>();
            try
            {
                if (File.Exists(recentPathsFile))
                {
                    using (StreamReader reader = new StreamReader(recentPathsFile))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            paths.Add(line);
                        }
                        reader.Close();
                    }
                }
                paths.Remove(path);
                paths.Insert(0, path);
                if (paths.Count > 5)
                {
                    paths = paths.Take(5).ToList();
                }
                using (StreamWriter writer = new StreamWriter(recentPathsFile))
                {
                    foreach (string p in paths)
                    {
                        writer.WriteLine(p);
                    }
                    writer.Close();
                }
            } catch (Exception ex)
            {
                Console.Error.WriteLine($"Error managing recent paths: {ex.Message}");
            }
        }

        /// <summary>
        /// Gets the recently opened file paths.
        /// </summary>
        /// <returns>
        /// A <see cref="List{String}"/> containing the recent file paths.
        /// </returns>
        public static List<string> GetRecentPaths()
        {
            List<string> paths = new List<string>();
            try
            {
                if (File.Exists(recentPathsFile))
                {
                    using (StreamReader reader = new StreamReader(recentPathsFile))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            paths.Add(line);
                        }
                        reader.Close();
                    }
                }
            } catch (Exception ex)
            {
                Console.Error.WriteLine($"Error reading recent paths: {ex.Message}");
            }
            return paths;
        }
    }
}
