using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;

namespace AdvertisingProfitControlData
{
    public class Backup
    {
        public static readonly string DefaultBackupLocation = Path.GetPathRoot(Environment.SystemDirectory) + @"Users\" + Environment.UserName + @"\AppData\Local\APC\Backups\";
        public static readonly string DefaultBackupExtension = "apcdbbak";
        public string ErrorMessage = string.Empty;

        public bool SingleFileBackup(string optionalBackupFilePath = "")
        {
            var defaultBackupFile = DefaultBackupLocation + DateTime.Now.ToString("yy-MM-dd") + "." +  DefaultBackupExtension;
            var sqlConStrBuilder = new SqlConnectionStringBuilder(AdvertisingProfitControlDbContext.ConnectionString);
            try
            {
                using (var s = new SqlConnection(sqlConStrBuilder.ConnectionString))
                {
                    var query = $"BACKUP DATABASE {sqlConStrBuilder.InitialCatalog} TO DISK='{defaultBackupFile}'";

                    using (var command = new SqlCommand(query, s))
                    {
                        s.Open();
                        command.ExecuteNonQuery();
                        if (optionalBackupFilePath == string.Empty) return true;
                        command.CommandText =
                            $"BACKUP DATABASE {sqlConStrBuilder.InitialCatalog} TO DISK='{optionalBackupFilePath + DateTime.Now.ToString("yy-MM-dd") + "." + DefaultBackupExtension}'";
                        command.ExecuteNonQuery();
                    }
                }

                return true;
            }
            catch (SqlException e)
            {
                ErrorMessage = e.Message;
                return false;
            }
        }

        public List<FileInfo> GetSingleFileBackupFilesList()
        {
            var directoryInfo = new DirectoryInfo(DefaultBackupLocation);
            var files = directoryInfo.GetFiles("*." + DefaultBackupExtension);
            return files.ToList();
        }
    }
}
