using System;
using System.IO;
using System.Windows.Forms;
using AdvertisingProfitControlData;

namespace AdvertsingProfitControl
{
    public partial class DatabaseRecovery : Form
    {
        public bool RestoredDatabase;       

        public DatabaseRecovery()
        {
            InitializeComponent();
            exisitingBackupsListView.ItemSelectionChanged += UpdateRestoreLocationTextBoxOnItemSelectionChange;
            restoreLocationTextBox.TextChanged += UpdateRestoreButtonOnRestoreLocationTextChange;
            //Grab the list of backups and fill the list box.
            var headerColumn = new ColumnHeader
            {
                Width = exisitingBackupsListView.Width - 10,
                TextAlign = HorizontalAlignment.Center
            };
            exisitingBackupsListView.Columns.Add(headerColumn);
            UpdateBackupList();
        }

        private void UpdateRestoreButtonOnRestoreLocationTextChange(object sender, EventArgs e)
        {
            restoreBackupButton.Enabled = restoreLocationTextBox.Text.Length != 0;
        }

        private void UpdateRestoreLocationTextBoxOnItemSelectionChange(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            //Update the restore location text box when an item is selected.
            restoreLocationTextBox.Text = ((FileInfo) e.Item.Tag).FullName;
            deleteBackupFileButton.Enabled = true;
        }

        private void UpdateBackupList()
        {
            var backup = new Backup();
            var fileList = backup.GetSingleFileBackupFilesList();
            exisitingBackupsListView.Items.Clear();

            if (fileList.Count > 0)
            {
                foreach (var file in fileList)
                {
                    var item = new ListViewItem
                    {
                        Text = file.Name,
                        Tag = file
                    };
                    exisitingBackupsListView.Items.Add(item);
                }
                exisitingBackupsListView.Columns[0].Text = @"Current Backups";
            }
            else
            {
                exisitingBackupsListView.Columns[0].Text = @"No Backups Exist";          
            }
        }

        private void CreateBackupOnButtonClick(object sender, EventArgs e)
        {
            var backup = new Backup();
            var customBackupLocation = string.Empty;

            if (!string.IsNullOrWhiteSpace(customBackupLocationTextBox.Text))
            {
                //Check to see if the folder selected or typed exists.
                var folder = new DirectoryInfo(customBackupLocationTextBox.Text);

                if (folder.Exists)
                {
                    customBackupLocation = customBackupLocationTextBox.Text;
                }
                else
                {
                    MessageBox.Show(
                        @"The selected backup folder doesn't exist. Please choose a different folder to store the backup.",
                        @"Backup Folder Location Invalid", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    backupResultLabel.Text = @"Custom backup location invalid.";
                    return;
                }
            }

            if (backup.SingleFileBackup(customBackupLocation))
            {
                backupResultLabel.Text = @"Successfully created backup(s).";
                customBackupLocationTextBox.Text = string.Empty;
            }
            else
            {
                MessageBox.Show(backup.ErrorMessage, @"Failed to Create Backup", MessageBoxButtons.OK, MessageBoxIcon.Error);
                backupResultLabel.Text = @"Failed to create backup(s).";
            }

            UpdateBackupList();
        }

        private void UpdateCustomBackupLocationOnBackupLocationButtonClick(object sender, EventArgs e)
        {
            var dialog = new FolderBrowserDialog {Description = @"Select a folder to place the backup file into."};
            dialog.ShowDialog();

            if (dialog.SelectedPath != string.Empty)
            {
                customBackupLocationTextBox.Text = dialog.SelectedPath;
            }
        }

        private void UpdateRestoreLocationOnCustomBackupLocationButtonClick(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                Multiselect = false,
                Filter = @"Backup Files | *." + Backup.DefaultBackupExtension,
                Title = @"Select your backup file to restore from."
            };

            dialog.ShowDialog();

            restoreLocationTextBox.Text = dialog.FileName;
        }

        private void RestoreSelectedBackupOnBackupRestoreButtonClick(object sender, EventArgs e)
        {
            var restore = new Restore();
            //Check for the file's existence before proceeding.
            if (!File.Exists(restoreLocationTextBox.Text))
            {
                MessageBox.Show(@"Database backup file could not be found at the location" + Environment.NewLine + @"'" + restoreLocationTextBox.Text + @"'.", @"Database Backup File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                restoreInfoLabel.Text = @"Restore file location invalid.";
                return;
            }

            if (restore.SingleFileRestore(restoreLocationTextBox.Text))
            {
                restoreResultLabel.Text = @"Successfully restored the database.";
                restoreLocationTextBox.Text = string.Empty;
                RestoredDatabase = true;
            }
            else
            {
                MessageBox.Show(restore.ErrorMessage, @"Failed to Restore Backup", MessageBoxButtons.OK, MessageBoxIcon.Error);
                restoreInfoLabel.Text = @"Failed to restore the database.";
            }
        }

        private void deleteBackupFileButton_Click(object sender, EventArgs e)
        {
            if (exisitingBackupsListView.SelectedItems.Count == 0)
            {
                deleteBackupFileButton.Enabled = false;
                return;
            }

            var selectedItem = exisitingBackupsListView.SelectedItems[0];
            var fileInfo = (FileInfo) selectedItem.Tag;

            try
            {
                File.Delete(fileInfo.FullName);
                restoreLocationTextBox.Text = string.Empty;
                deleteBackupFileButton.Enabled = false;
            }
            catch (IOException exception)
            {
                MessageBox.Show(exception.Message, @"Failed to Delete File " + fileInfo.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            UpdateBackupList();
        }
    }
}
