﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using IRO.BabyGotBackground.Properties;
using IRO.BabyGotBackground.Providers;
using IRO.BabyGotBackground.Utility;

namespace IRO.BabyGotBackground.UI
{
    public sealed class BusinessLayer
    {
        private static readonly string COMPANY_NAME = "IRO";
        private static readonly string APPLICATION_NAME = "BabyGotBackground";
        private static readonly string EXPLORER_PROCESS_NAME = "explorer.exe";

        /// <summary>
        /// Initializes a new instance of the <see cref="BusinessLayer" /> class.
        /// </summary>
        public BusinessLayer()
        {
            ApplicationDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), COMPANY_NAME, APPLICATION_NAME);
            if (!Directory.Exists(ApplicationDataPath))
            {
                Directory.CreateDirectory(ApplicationDataPath);
            }
        }

        /// <summary>
        /// Gets or sets the application data path.
        /// </summary>
        /// <value>
        /// The application data path.
        /// </value>
        public string ApplicationDataPath { get; set; }

        /// <summary>
        /// Gets the current background information.
        /// </summary>
        /// <returns></returns>
        public string GetCurrentBackgroundInformation(IBackgroundProvider backgroundProvider)
        {
            return backgroundProvider.BackgroundDescription;
        }

        /// <summary>
        /// Saves the background to disk.
        /// </summary>
        public void SaveBackgroundToDisk()
        {
            FileUtility.SaveToDisk(ApplicationDataPath);
        }

        /// <summary>
        /// Opens the application directory.
        /// </summary>
        public void OpenApplicationDirectory()
        {
            Process.Start(EXPLORER_PROCESS_NAME, ApplicationDataPath);
        }

        /// <summary>
        /// Performs the background update.
        /// </summary>
        /// <exception cref="System.Exception">The background provider has not been selected</exception>
        public async void UpdateBackgroundAsync(IBackgroundProvider backgroundProvider, bool force = false)
        {
            if (Settings.Default.EnableAutomaticUpdates || force)
            {
                string backgroundPath = await backgroundProvider.DownloadBackgroundAsync(null, this);
                BackgroundHelper.SetDesktopBackground(backgroundPath, DesktopBackgroundStyle.Filled);
            }
        }
    }
}
