using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml.Linq;
using Umbraco.Core.Cache;
namespace Umbraco.Core.Services
{
///
/// Exposes the XDocument sources from files for the default localization text service and ensure caching is taken care of
///
public class LocalizedTextServiceFileSources
{
private readonly IRuntimeCacheProvider _cache;
private readonly DirectoryInfo _fileSourceFolder;
public LocalizedTextServiceFileSources(IRuntimeCacheProvider cache, DirectoryInfo fileSourceFolder)
{
if (cache == null) throw new ArgumentNullException("cache");
if (fileSourceFolder == null) throw new ArgumentNullException("fileSourceFolder");
_cache = cache;
_fileSourceFolder = fileSourceFolder;
}
///
/// returns all xml sources for all culture files found in the folder
///
///
public IDictionary> GetXmlSources()
{
var result = new Dictionary>();
foreach (var fileInfo in _fileSourceFolder.GetFiles("*.xml"))
{
var localCopy = fileInfo;
var filename = Path.GetFileNameWithoutExtension(localCopy.FullName).Replace("_", "-");
var culture = CultureInfo.GetCultureInfo(filename);
//get the lazy value from cache
result.Add(culture, new Lazy(() => _cache.GetCacheItem(
string.Format("{0}-{1}", typeof (LocalizedTextServiceFileSources).Name, culture.TwoLetterISOLanguageName), () =>
{
using (var fs = localCopy.OpenRead())
{
return XDocument.Load(fs);
}
}, isSliding: true, timeout: TimeSpan.FromMinutes(10), dependentFiles: new[] {localCopy.FullName})));
}
return result;
}
}
}