﻿// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin

// Author: Maxim Kuzmin

using Autofac;
using Autofac.Core;
using Makc2017.Core.App;
using Microsoft.Extensions.Caching.Memory;

namespace Makc2017.Core.Caching
{
    /// <summary>
    /// Ядро. Кэширование. Плагин.
    /// </summary>
    public class CoreCachingPlugin : ICoreCachingPlugin
    {
        #region Properties

        /// <summary>
        /// Поставщик конфигурации.
        /// </summary>
        private CoreCachingConfigurationProvider ConfigurationProvider { get; set; }

        /// <summary>
        /// Конфигурация.
        /// </summary>
        private CoreCachingConfig Config { get; set; }

        /// <summary>
        /// Контекст.
        /// </summary>
        private ICoreCachingContext Context { get; set; }

        /// <summary>
        /// Распознаватель зависимостей.
        /// </summary>
        public IModule Resolver { get; private set; }

        /// <summary>
        /// Кэш в памяти.
        /// </summary>
        public IMemoryCache MemoryCache { get; private set; }

        #endregion Properties

        #region Constructors

        /// <summary>
        /// Конструктор.
        /// </summary>
        public CoreCachingPlugin()
        {
            Resolver = new CoreCachingResolver();
        }

        #endregion Constructors

        #region Public methods

        /// <summary>
        /// Инициализировать.
        /// </summary>
        /// <param name="pluginEnvironment">Окружение плагинов.</param>
        public void Init(CoreAppPluginEnvironment pluginEnvironment)
        {
            ConfigurationProvider.Init(pluginEnvironment.BasePath, new[] { @"Makc2017.Core.Caching\config.json" });

            Config.Init(ConfigurationProvider);

            Context.Init(MemoryCache, Config);
        }

        /// <summary>
        /// Распознать зависимости.
        /// </summary>
        /// <param name="componentContext">Контекст компонентов.</param>
        public void Resolve(IComponentContext componentContext)
        {
            ConfigurationProvider = componentContext.Resolve<CoreCachingConfigurationProvider>();
            Config = componentContext.Resolve<CoreCachingConfig>();
            Context = componentContext.Resolve<ICoreCachingContext>();
            MemoryCache = componentContext.Resolve<IMemoryCache>();
        }

        #endregion Public methods
    }
}