﻿namespace Porthole
{
    using System.Collections.Generic;
    using Windows.Storage;

    /// <summary>
    /// Handles the creation of <see cref="SettingsContainer"/> instances.
    /// </summary>
    public static class Settings
    {
        /// <summary>
        /// Attempts to create the provided settings container.
        /// </summary>
        /// <exception cref="System.Exception">Thrown if "Existing" is passed and the container doesn't exist.</exception>
        /// <param name="name">The name for the settings container</param>
        /// <param name="location">Where the settings should be stored</param>
        /// <param name="disposition">How creation of the container should be handled</param>
        /// <returns>The newly created container</returns>
        public static SettingsContainer CreateContainer(string name, SettingsLocation location, SettingsCreateDisposition disposition)
        {
            var container = GetDataContainer(location);
            container.CreateContainer(name, GetDisposition(disposition));
            return new SettingsContainer(name, GetDataContainer(location));
        }

        /// <summary>
        /// Deletes the provided settings container
        /// </summary>
        /// <param name="name">The name of the settings container</param>
        /// <param name="location">Where the settings are stored</param>
        public static void DeleteContainer(string name, SettingsLocation location)
        {
            var container = GetDataContainer(location);
            container.DeleteContainer(name);
        }

        private static Dictionary<string, object> ConvertToDictionary(ApplicationDataContainer applicationDataContainer)
        {
            var dict = new Dictionary<string, object>();
            foreach (var item in applicationDataContainer.Values)
            {
                dict.Add(item.Key, item.Value);
            }

            return dict;
        }

        private static ApplicationDataContainer GetDataContainer(SettingsLocation location)
        {
            if (location == SettingsLocation.Local)
            {
                return ApplicationData.Current.LocalSettings;
            }
            else
            {
                return ApplicationData.Current.RoamingSettings;
            }
        }

        private static ApplicationDataCreateDisposition GetDisposition(SettingsCreateDisposition disposition)
        {
            if (disposition == SettingsCreateDisposition.Always)
            {
                return ApplicationDataCreateDisposition.Always;
            }
            else
            {
                return ApplicationDataCreateDisposition.Existing;
            }
        }
    }
}