using LiteDB;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeviceId.Components;
using DeviceId;
using Tango.Core;
namespace Tango.FSE.BL
{
///
/// Represents a disk cache manager.
///
public class DiskCacheManager : ExtendedObject, IDisposable
{
public class DiskCacheContext : IDisposable
{
public LiteDatabase Database { get; private set; }
public DiskCacheContext(LiteDatabase database)
{
Database = database;
}
public void Dispose()
{
//Do Nothing.
}
}
private LiteDatabase _database;
///
/// Gets the database file path.
///
public String DatabasePath { get; private set; }
private static DiskCacheManager _default;
///
/// Gets the default instance.
///
public static DiskCacheManager Default
{
get
{
if (_default == null)
{
_default = new DiskCacheManager(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Twine", "Tango", "Cache", BuildProvider.Build.ToDescription(), Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName) + ".cache"));
}
return _default;
}
}
///
/// Initializes a new instance of the class.
///
/// The database path.
public DiskCacheManager(String databasePath)
{
DatabasePath = databasePath;
}
///
/// Creates a new disk cache context.
///
///
public DiskCacheContext CreateContext()
{
if (_database == null)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(DatabasePath));
var deviceId = new DeviceIdBuilder().AddMotherboardSerialNumber().ToString();
_database = new LiteDatabase($"Filename={DatabasePath};Password={deviceId}");
}
catch (Exception ex)
{
throw LogManager.Log(ex, "Error accessing disk cache.");
}
}
return new DiskCacheContext(_database);
}
///
/// Finalizes an instance of the class.
///
~DiskCacheManager()
{
Dispose();
}
///
/// Releases unmanaged and - optionally - managed resources.
///
public void Dispose()
{
if (_database != null)
{
try
{
_database.Dispose();
_database = null;
}
catch { }
}
}
}
}