using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataOrganizer
{
    public partial class ProfileManager : Form
    {
        private string MachineNameLabelText { get; } = "The Machine Name property determines what profile will be loaded automatically.\r\nCurrently: '{0}'.";
        private bool IsUpdating { get; set; }
        private ContextMenu FolderGroupListContextMenu { get; set; } = new ContextMenu();
        private ListViewItem SelectedItem { get; set; }

        public ProfileManager()
        {
            InitializeComponent();

            var deleteMenuItem = new MenuItem("Delete");
            FolderGroupListContextMenu.MenuItems.Add(deleteMenuItem);

            ProfilesComboBox.SelectedIndexChanged += ProfilesComboBox_SelectedIndexChanged;
            ProfileNameTextBox.TextChanged += ToggleAddOrUpdateButton;
            NewContentLocationTextBox.TextChanged += ToggleAddOrUpdateButton;
            MachineNameTextBox.TextChanged += MachineNameTextBox_TextChanged;
            FolderGroupPathTextBox.TextChanged += ToggleGroupInsertButton;
            FolderGroupListView.MouseClick += FolderGroupListView_MouseClick;
            deleteMenuItem.Click += DeleteMenuItem_Click;

            UpdateProfileComboBox();
        }

        private void FolderGroupListView_MouseClick(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)
            {
                SelectedItem = FolderGroupListView.GetItemAt(e.X, e.Y);
                FolderGroupListContextMenu.Show(FolderGroupListView, e.Location);
            }
        }

        private void DeleteMenuItem_Click(object sender, EventArgs e)
        {
            if(IsUpdating)
            {
                var result = MessageBox.Show("Are you sure you want to delete this group? Doing so will delete all records associated with it?", "Confirm Group Deletion", MessageBoxButtons.YesNo);

                if(result == DialogResult.Yes)
                {
                    var db = new DB();
                    var currentIndex = ProfilesComboBox.SelectedIndex;

                    db.DeleteFolderGroup((DB.FolderGroup) SelectedItem.Tag);

                    UpdateProfileComboBox();

                    ProfilesComboBox.SelectedIndex = currentIndex;
                }
            }
            else
            {
                FolderGroupListView.Items.Remove(FolderGroupListView.SelectedItems[0]);
            }

            SelectedItem = null;
        }

        private void MachineNameTextBox_TextChanged(object sender, EventArgs e)
        {
            if (MachineNameTextBox.Text.Length > 0)
                MachineNameLabel.Text = string.Format(MachineNameLabelText, MachineNameTextBox.Text);
            else
                MachineNameLabel.Text = string.Format(MachineNameLabelText, Environment.MachineName);
        }

        private void ToggleAddOrUpdateButton(object sender, EventArgs e)
        {
            if (ProfileNameTextBox.Text != string.Empty && NewContentLocationTextBox.Text != string.Empty)
                AddOrUpdateProfileButton.Enabled = true;
            else 
                AddOrUpdateProfileButton.Enabled = false;
        }

        private void ToggleGroupInsertButton(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(FolderGroupPathTextBox.Text))
                InsertGroupName.Enabled = true;
            else
                InsertGroupName.Enabled = false;
        }

        private void UpdateProfileComboBox()
        {
            var db = new DB();

            var profiles = db.GetProfiles();
            ProfilesComboBox.Items.Clear();
            ProfilesComboBox.Tag = null;
            ProfilesComboBox.Items.Add("Add New Profile");
            ProfilesComboBox.SelectedIndex = 0;
            FolderGroupListView.Items.Clear();

            if (profiles.Count == 0)
            {
                ProfilesComboBox.Enabled = false;
                return;
            }

            ProfilesComboBox.Enabled = true;

            foreach (var profile in profiles)
            {
                ProfilesComboBox.Items.Add(profile.Name);
            }

            ProfilesComboBox.Tag = profiles;
        }

        private void AddOrUpdateProfileButton_Click(object sender, EventArgs e)
        {
            var machineName = Environment.MachineName;
            var db = new DB();

            if(!string.IsNullOrWhiteSpace(MachineNameTextBox.Text))
            {
                machineName = MachineNameTextBox.Text;
            }

            if (!IsUpdating)
            {
                var folders = new List<DB.FolderGroup>();

                foreach(ListViewItem node in FolderGroupListView.Items)
                {
                    folders.Add(new DB.FolderGroup
                    {
                        Name = node.SubItems[0].Text,
                        Path = node.SubItems[1].Text
                    });
                }

                db.InsertNewProfile(new DB.Profile { Name = ProfileNameTextBox.Text, DefaultNewContentFolder = NewContentLocationTextBox.Text, MachineName = machineName, FolderGroups = folders });

                UpdateProfileComboBox();
            }
            else
            {
                GetCurrentProfile(out DB.Profile profile);
                profile.Name = ProfileNameTextBox.Text;
                profile.DefaultNewContentFolder = NewContentLocationTextBox.Text;
                profile.MachineName = MachineNameTextBox.Text;
                db.UpdateProfile(profile);
            }

            UpdateProfileComboBox();
        }

        private void ProfilesComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            FolderGroupListView.Items.Clear();

            if (ProfilesComboBox.SelectedIndex == 0)
            {
                ProfileNameTextBox.Text = string.Empty;
                NewContentLocationTextBox.Text = string.Empty;
                MachineNameTextBox.Text = string.Empty;
                AddOrUpdateProfileButton.Text = "Add";
                AddOrUpdateProfileButton.Enabled = false;
                MachineNameLabel.Text = string.Format(MachineNameLabelText, Environment.MachineName);
                IsUpdating = false;
                DeleteProfileButton.Enabled = false;
                return;
            }

            IsUpdating = true;

            GetCurrentProfile(out DB.Profile profile);

            ProfileNameTextBox.Text = profile.Name;
            NewContentLocationTextBox.Text = profile.DefaultNewContentFolder;
            MachineNameTextBox.Text = profile.MachineName;
            DeleteProfileButton.Enabled = true;

            MachineNameLabel.Text = string.Format(MachineNameLabelText, profile.MachineName);

            AddOrUpdateProfileButton.Text = "Update";

            if(profile.FolderGroups != null)
            {
                foreach(var group in profile.FolderGroups)
                {
                    var item = new ListViewItem(group.Name);
                    item.SubItems.Add(group.Path);
                    item.Tag = group;

                    FolderGroupListView.Items.Add(item);
                }
            }
        }

        private void InsertGroupName_Click(object sender, EventArgs e)
        {
            var dir = new DirectoryInfo(FolderGroupPathTextBox.Text);
            var groupName = dir.Name;

            if (!FolderGroupListView.Items.ContainsKey(groupName))//!FolderGroupsTreeView.Nodes.ContainsKey(groupName))
            {
                var item = new ListViewItem(groupName);
                item.SubItems.Add(FolderGroupPathTextBox.Text);

                FolderGroupListView.Items.Add(item);

                if (IsUpdating)
                {
                    var db = new DB();

                    GetCurrentProfile(out DB.Profile profile);

                    var newId = db.InsertNewFolderGroup(profile, groupName, FolderGroupPathTextBox.Text);

                    profile.FolderGroups.Add(new DB.FolderGroup { Name = groupName, Id = newId, Path = FolderGroupPathTextBox.Text });
                }
            }

            FolderGroupPathTextBox.Text = string.Empty;
            FolderGroupPathButton.Focus();
        }

        private bool GetCurrentProfile(out DB.Profile profile)
        {
            profile = new DB.Profile();

            if (!IsUpdating) return false;

            profile = ((List<DB.Profile>)ProfilesComboBox.Tag)[ProfilesComboBox.SelectedIndex - 1];

            return true;
        }

        private void DeleteProfileButton_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("Are you sure? This will delete all file records (not files on disk), groups and any customization data set in this profile.", "Wipe Profile", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

            if(result == DialogResult.Yes)
            {
                var db = new DB();
                GetCurrentProfile(out DB.Profile profile);

                db.DeleteProfile(profile);

                UpdateProfileComboBox();
            }
        }

        private void FolderGroupPathButton_Click(object sender, EventArgs e)
        {
            var dialog = new FolderBrowserDialog();

            if(dialog.ShowDialog() == DialogResult.OK)
            {
                FolderGroupPathTextBox.Text = dialog.SelectedPath;
            }
        }
    }
}
