using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Data.Sqlite;
using System.Reflection;
using System.Windows.Forms;
using System.Configuration;
using System.Diagnostics;

namespace DataOrganizer
{
    public class DB
    {
        public static string DatabasePath { get; private set; }
        public static string ConnectionString { get; private set; }
        public static string TempScriptLocal = "Y:\\Database Template.sql";

        public DB()
        {
            DatabasePath = $"{new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).Directory.FullName}\\Organizer Data\\Main.sqlite";

            ConnectionString = $"Data Source={DatabasePath}";

            if (!Directory.Exists(new FileInfo(DatabasePath).Directory.FullName))
            {
                Directory.CreateDirectory(new FileInfo(DatabasePath).Directory.FullName);
                CreateDatabase();
            }
        }

        private void CreateDatabase()
        {
            //TODO: this is tmp
            var query = File.ReadAllText(TempScriptLocal);

            using (var connection = new SqliteConnection(ConnectionString))
            {
                using(var command = new SqliteCommand(query, connection))
                {
                    connection.Open();

                    command.ExecuteNonQuery();
                }
            }
        }

        public List<Profile> GetProfiles()
        {
            var query = "SELECT * FROM profile";

            var profiles = new List<Profile>();

            using (var connection = new SqliteConnection(ConnectionString))
            {
                using (var command = new SqliteCommand(query, connection))
                {
                    connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        profiles.Add(new Profile
                        {
                            Name = reader["profile_name"].ToString(),
                            DefaultNewContentFolder = reader["default_new_content_folder_name"].ToString(),
                            MachineName = reader["machine_name"].ToString(),
                            Id = Convert.ToInt32(reader["profile_id"]),
                            FolderGroups = new List<FolderGroup>()
                        });
                    }

                    reader.Close();

                    command.CommandText = "SELECT root_id, name, path FROM folder_root WHERE profile_id = @ID ORDER BY name";

                    foreach(var profile in profiles)
                    {
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("ID", profile.Id);

                        reader = command.ExecuteReader();

                        while(reader.Read())
                        {
                            profile.FolderGroups.Add(new FolderGroup
                            {
                                Name = reader["name"].ToString(),
                                Id = Convert.ToInt32(reader["root_id"]),
                                Path = reader["path"].ToString()
                            });
                        }

                        reader.Close();
                    }
                }
            }

            return profiles;
        }

        public bool UpdateProfile(Profile profile)
        {
            var query = @"UPDATE main.profile SET machine_name = @MachineName, default_new_content_folder_name = @DefaultPath, profile_name = @Name WHERE profile_id = @ID";

            using (var connection = new SqliteConnection(ConnectionString))
            {
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("MachineName", profile.MachineName);
                    command.Parameters.AddWithValue("DefaultPath", profile.DefaultNewContentFolder);
                    command.Parameters.AddWithValue("Name", profile.Name);
                    command.Parameters.AddWithValue("ID", profile.Id);

                    connection.Open();

                    command.ExecuteNonQuery();
                }
            }

            return true;
        }

        public int InsertNewProfile(Profile profile)
        {
            var query = @"INSERT INTO main.profile (machine_name, default_new_content_folder_name, profile_name) VALUES (@MachineName, @DefaultPath, @Name)";
            var id = -1;

            using (var connection = new SqliteConnection(ConnectionString))
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction())
                {
                    using (var command = new SqliteCommand(query, connection, transaction))
                    {
                        command.Parameters.AddWithValue("MachineName", profile.MachineName);
                        command.Parameters.AddWithValue("DefaultPath", profile.DefaultNewContentFolder);
                        command.Parameters.AddWithValue("Name", profile.Name);

                        command.ExecuteNonQuery();

                        command.CommandText = "SELECT MAX(profile_id) FROM main.profile";

                        id = Convert.ToInt32(command.ExecuteScalar());

                        command.CommandText = "INSERT INTO main.folder_root (name, path, profile_id) VALUES (@Name, @Path, @ProfileID)";

                        if (profile.FolderGroups != null)
                        {
                            foreach(var group in profile.FolderGroups)
                            {
                                command.Parameters.Clear();
                                command.Parameters.AddWithValue("Name", group.Name);
                                command.Parameters.AddWithValue("Path", group.Path);
                                command.Parameters.AddWithValue("ProfileID", id);

                                command.ExecuteNonQuery();
                            }
                        }
                    }

                    transaction.Commit();
                }
            }

            return id;
        }

        public int InsertNewFolderGroup(Profile profile, string name, string path)
        {
            var query = @"INSERT INTO main.folder_root (name, path, profile_id) VALUES (@Name, @Path, @ProfileID)";
            var id = -1;

            using (var connection = new SqliteConnection(ConnectionString))
            {
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("Name", name);
                    command.Parameters.AddWithValue("Path", path);
                    command.Parameters.AddWithValue("ProfileID", profile.Id);

                    connection.Open();

                    command.ExecuteNonQuery();

                    command.CommandText = @"SELECT MAX(root_id) FROM main.folder_root";

                    id = Convert.ToInt32(command.ExecuteScalar());
                }
            }

            return id;
        }

        public bool UpdateFolderGroup(string newName, string path)
        {
            var query = @"UPDATE main.folder_root SET name = @Name, path = @Path";

            using (var connection = new SqliteConnection(ConnectionString))
            {
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("Name", newName);
                    command.Parameters.AddWithValue("Path", path);

                    connection.Open();

                    command.ExecuteNonQuery();
                }
            }

            return true;
        }

        public bool DeleteFolderGroup(FolderGroup folderGroup)
        {
            var query = string.Format("DELETE FROM main.file WHERE folder_root_id = {0}", folderGroup.Id);

            using(var connection = new SqliteConnection(ConnectionString))
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction())
                {
                    using(var command = new SqliteCommand(query, connection, transaction))
                    {
                        command.ExecuteNonQuery();

                        command.CommandText = string.Format("DELETE FROM main.folder_root WHERE root_id = {0}", folderGroup.Id);

                        command.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }
            }

            return true;
        }

        public bool DeleteProfile(Profile profile)
        {
            var query = string.Format("DELETE FROM main.file WHERE profile_id = {0}", profile.Id);

            using (var connection = new SqliteConnection(ConnectionString))
            {
                connection.Open();

                using (var transaction = connection.BeginTransaction())
                {
                    using (var command = new SqliteCommand(query, connection, transaction))
                    {
                        command.ExecuteNonQuery();

                        command.CommandText = string.Format("DELETE FROM main.folder_root WHERE profile_id = {0}", profile.Id);

                        command.ExecuteNonQuery();

                        command.CommandText = string.Format("DELETE FROM main.profile WHERE profile_id = {0}", profile.Id);

                        command.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }
            }

            return true;
        }

        public struct Profile
        {
            public string Name;
            public string DefaultNewContentFolder;
            public string MachineName;
            public int Id;
            public List<FolderGroup> FolderGroups;
        }

        public struct FolderGroup
        {
            public int Id;
            public string Name;
            public string Path;
        }
    }
}
