using DaireApplication.DataBase;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;

namespace AvaloniaApplication1.DataBase
{
    public class RecipeTable
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public float TankTemp { get; set; } = 0;
        public float FountainTemp { get; set; } = 0;
        public bool? Mixer { get; set; } = false;
        public bool? Fountain { get; set; }=false;
        public bool? MoldHeater { get; set; }=false;
        public bool? Vibration { get; set; } = false;
        public bool? VibHeater { get; set; } = false;
        public bool? Pedal { get; set; } = false;
        public int PedalOnTime { get; set; } = 0;
        public int PedalOffTime { get; set; } = 0;
        public float HeatingGoal { get; set; } = 46;
        public float CoolingGoal { get; set; } = 27;
        public float PouringGoal { get; set; } = 30;

        public RecipeTable()
        {
            Mixer = null;
            Fountain = null;
            MoldHeater = null;
            Vibration = null;
            VibHeater = null;
            Pedal = null;
        }


        public List<RecipeTable> ReadRecipes()
        {
            string filePath = DataPathManager.GetDataFilePath("Recipe.csv");
            List<RecipeTable> recipes = new List<RecipeTable>();

            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    // Skip header
                    string header = reader.ReadLine();
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        string[] columns = line.Split(',');
                        recipes.Add(new RecipeTable
                        {
                            Id = int.Parse(columns[0]),
                            Name = columns[1],
                            TankTemp = float.Parse(columns[2]),
                            FountainTemp = float.Parse(columns[3]),
                            Mixer = columns[4] == "1",
                            Fountain = columns[5] == "1",
                            MoldHeater = columns[6]=="1",
                            Vibration = columns[7] == "1",
                            VibHeater = columns[8]== "1",
                            Pedal = columns[9]=="1",
                            PedalOnTime = int.Parse(columns[10]),
                            PedalOffTime = int.Parse(columns[11]),
                            HeatingGoal = float.Parse(columns[12]),
                            CoolingGoal = float.Parse(columns[13]),
                            PouringGoal = float.Parse(columns[14]),
                        });
                    }
                }
                return recipes;
            }
            else
            {
                return null;
            }
        }
        public bool DoesNameExist(string searchName)
        {
            string filePath = DataPathManager.GetDataFilePath("Recipe.csv");

            if (!File.Exists(filePath))
                return false;

            string[] lines = File.ReadAllLines(filePath);

            return lines
                .Select(line => line.Split(','))
                .Where(columns => columns.Length > 1)
                .Any(columns => string.Equals(columns[1].Trim(), searchName, StringComparison.OrdinalIgnoreCase));
        }

        public int GetMaxId()
        {
            string filePath = DataPathManager.GetDataFilePath("Recipe.csv");

            if (File.Exists(filePath))
            {
                string[] lines = File.ReadAllLines(filePath);
                int maxId = lines
                    .Select(line => line.Split(','))
                    .Where(columns => columns.Length > 0)
                    .Select(columns => int.TryParse(columns[0], out int id) ? id : 0)
                    .Max();
                return maxId;
            }
            else
            {
                return -1;
            }
        }
        public RecipeTable ReadRecipesById(string id)
        {
            string filePath = DataPathManager.GetDataFilePath("Recipe.csv");
            RecipeTable recipe = new RecipeTable();

            if (File.Exists(filePath))
            {
                string[] lines = File.ReadAllLines(filePath);

                foreach (string line in lines)
                {
                    string[] columns = line.Split(',');

                    if (columns[0] == id)
                    {
                        recipe.Id = int.Parse(columns[0]);
                        recipe.Name = columns[1];
                        recipe.TankTemp = float.Parse(columns[2]);
                        recipe.FountainTemp = float.Parse(columns[3]);
                        recipe.Mixer = columns[4] == "1";
                        recipe.Fountain = columns[5] == "1";
                        recipe.MoldHeater = columns[6] == "1";
                        recipe.Vibration = columns[7] == "1";
                        recipe.VibHeater = columns[8] == "1";
                        recipe.Pedal = columns[9] == "1";
                        recipe.PedalOnTime = int.Parse(columns[10]);
                        recipe.PedalOffTime = int.Parse(columns[11]);
                        recipe.HeatingGoal = float.Parse(columns[12]);
                        recipe.CoolingGoal = float.Parse(columns[13]);
                        recipe.PouringGoal = float.Parse(columns[14]);
                        return recipe;
                    }
                }
                return null;
            }
            else
            {
                return null;
            }
        } 
        public bool AddRecipe(RecipeTable data)
        {
            string filePath = DataPathManager.GetDataFilePath("Recipe.csv");

            if (File.Exists(filePath))
            {
                string newEntry = string.Join(",", [GetMaxId() +1, data.Name,data.TankTemp, data.FountainTemp, data.Mixer.Value?"1":"0", data.Fountain.Value ? "1" : "0", data.MoldHeater.Value ? "1" : "0", data.Vibration.Value ? "1" : "0", data.VibHeater.Value ? "1" : "0", data.Pedal.Value ? "1":"0",data.PedalOnTime,data.PedalOffTime, data.HeatingGoal,data.CoolingGoal,data.PouringGoal]);

                File.AppendAllText(filePath, newEntry + Environment.NewLine);
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool DeleteRecipe(string id)
        {
            string filePath = DataPathManager.GetDataFilePath("Recipe.csv");

            if (File.Exists(filePath))
            {
                string[] lines = File.ReadAllLines(filePath);
                var filteredLines = lines.Where(line => !line.StartsWith(id + ",")).ToArray();

                File.WriteAllLines(filePath, filteredLines);
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool UpdateRecipe(RecipeTable updatedRecipe)
        {
            string filePath = DataPathManager.GetDataFilePath("Recipe.csv");

            if (!File.Exists(filePath))
                return false;

            string[] lines = File.ReadAllLines(filePath);
            bool recipeFound = false;

            for (int i = 1; i < lines.Length; i++)
            {
                string[] columns = lines[i].Split(',');

                if (columns.Length < 15)
                    continue;

                if (int.TryParse(columns[0], out int id) && id == updatedRecipe.Id)
                {
                    columns[1] = updatedRecipe.Name ?? "";
                    columns[2] = updatedRecipe.TankTemp.ToString(CultureInfo.InvariantCulture);
                    columns[3] = updatedRecipe.FountainTemp.ToString(CultureInfo.InvariantCulture);
                    columns[4] = (updatedRecipe.Mixer ?? false) ? "1" : "0";
                    columns[5] = (updatedRecipe.Fountain ?? false) ? "1" : "0";
                    columns[6] = (updatedRecipe.MoldHeater ?? false) ? "1" : "0";
                    columns[7] = (updatedRecipe.Vibration ?? false) ? "1" : "0";
                    columns[8] = (updatedRecipe.VibHeater ?? false) ? "1" : "0";
                    columns[9] = (updatedRecipe.Pedal ?? false) ? "1" : "0";
                    columns[10] = updatedRecipe.PedalOnTime.ToString();
                    columns[11] = updatedRecipe.PedalOffTime.ToString();
                    columns[12] = updatedRecipe.HeatingGoal.ToString(CultureInfo.InvariantCulture);
                    columns[13] = updatedRecipe.CoolingGoal.ToString(CultureInfo.InvariantCulture);
                    columns[14] = updatedRecipe.PouringGoal.ToString(CultureInfo.InvariantCulture);

                    lines[i] = string.Join(",", columns);
                    recipeFound = true;
                    break;
                }
            }

            if (recipeFound)
            {
                File.WriteAllLines(filePath, lines);
                return true;
            }

            return false;
        }

    }
}
