using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;

namespace Crysome.Server.Model;

public static class InventoryIconCache
{
	private static readonly Dictionary<string, BitmapImage> _apps = new Dictionary<string, BitmapImage>(StringComparer.OrdinalIgnoreCase);

	private static readonly Dictionary<string, BitmapImage> _banks = new Dictionary<string, BitmapImage>(StringComparer.OrdinalIgnoreCase);

	private static readonly Dictionary<string, BitmapImage> _casinos = new Dictionary<string, BitmapImage>(StringComparer.OrdinalIgnoreCase);

	private static bool _loaded;

	private static readonly object _loadLock = new object();

	public static BitmapImage GetApp(string id)
	{
		EnsureLoaded();
		_apps.TryGetValue(id ?? "", out var value);
		return value;
	}

	public static BitmapImage GetBank(string id)
	{
		EnsureLoaded();
		_banks.TryGetValue(id ?? "", out var value);
		return value;
	}

	public static BitmapImage GetCasino(string id)
	{
		EnsureLoaded();
		_casinos.TryGetValue(id ?? "", out var value);
		return value;
	}

	private static void EnsureLoaded()
	{
		if (_loaded)
		{
			return;
		}
		lock (_loadLock)
		{
			if (!_loaded)
			{
				_loaded = true;
				string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
				LoadFromDir(Path.Combine(baseDirectory, "inventory", "apps"), _apps);
				LoadFromDir(Path.Combine(baseDirectory, "inventory", "banks"), _banks);
				LoadFromDir(Path.Combine(baseDirectory, "inventory", "casinos"), _casinos);
			}
		}
	}

	private static void LoadFromDir(string dir, Dictionary<string, BitmapImage> cache)
	{
		if (!Directory.Exists(dir))
		{
			return;
		}
		string[] files = Directory.GetFiles(dir, "*.png");
		foreach (string path in files)
		{
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
			if (!cache.ContainsKey(fileNameWithoutExtension))
			{
				try
				{
					byte[] buffer = File.ReadAllBytes(path);
					BitmapImage bitmapImage = new BitmapImage();
					bitmapImage.BeginInit();
					bitmapImage.StreamSource = new MemoryStream(buffer);
					bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
					bitmapImage.EndInit();
					((Freezable)bitmapImage).Freeze();
					cache[fileNameWithoutExtension] = bitmapImage;
				}
				catch
				{
				}
			}
		}
	}
}
