using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Data.SqlClient;

namespace FilterTimers.Timers
{
    internal class DBBackupTimer
    {
        #region Timer Variables

        private Int32 Interval;

        #endregion

        private Boolean IsDone = true;

        public DBBackupTimer(Int32 I)
        {
            Interval = I;

            Thread NewThread = new Thread(delegate ()
            {
                while (true)
                {
                    if (IsDone) { Run(); }

                    Thread.Sleep(Interval * 1000);
                }
            });

            NewThread.Start();
        }

        private void Run()
        {
            IsDone = false;

            try
            {
                foreach (var BackupDirectory in new DirectoryInfo(String.Format("{0}\\Database Backups", AppDomain.CurrentDomain.BaseDirectory)).GetDirectories().OrderByDescending(CreationTime => CreationTime.CreationTime).Skip(Convert.ToInt32(Program.Auth.ConfigValues["TimersDBBTMBF"]))) { BackupDirectory.Delete(true); }

                String TimeNow = DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss");

                if (!Directory.Exists(String.Format("{0}\\Database Backups", AppDomain.CurrentDomain.BaseDirectory))) { Directory.CreateDirectory(String.Format("{0}\\Database Backups", AppDomain.CurrentDomain.BaseDirectory)); }

                if (!Directory.Exists(String.Format("{0}\\Database Backups\\{1}", AppDomain.CurrentDomain.BaseDirectory, TimeNow))) { Directory.CreateDirectory(String.Format("{0}\\Database Backups\\{1}", AppDomain.CurrentDomain.BaseDirectory, TimeNow)); }

                using (SqlCommand Command = Program.SQL.Connection.CreateCommand())
                {
                    for (Byte Counter = 1; Counter < Convert.ToByte(Program.Auth.ConfigValues["TimersDBBTC"]) + 1; Counter++)
                    {
                        Command.CommandText = String.Format("BACKUP DATABASE {0} TO DISK = '{1}\\Database Backups\\{2}\\{3}.bak'", Program.Auth.ConfigValues[String.Format("TimersDBBT{0}N", Counter)], AppDomain.CurrentDomain.BaseDirectory, TimeNow, Program.Auth.ConfigValues[String.Format("TimersDBBT{0}WN", Counter)]);
                        Command.CommandTimeout = 0;
                        Command.ExecuteNonQuery();

                        Program.SendConsoleText(ConsoleColor.Green, "Backed up database {0}.", Program.Auth.ConfigValues[String.Format("TimersDBBT{0}N", Counter)]);
                    }
                }
            }
            catch (Exception Error) { Program.SendConsoleText(ConsoleColor.Red, "Timers error - Database backup\n{0}", Error.ToString()); }

            IsDone = true;
        }
    }
}
