using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using PSProxmox.Models;
namespace PSProxmox.Templates
{
///
/// Manages VM templates for Proxmox VE.
///
public class TemplateManager
{
private static readonly string TemplateDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PSProxmox",
"Templates");
private static readonly Dictionary _templates = new Dictionary();
private static bool _initialized = false;
///
/// Initializes the template manager.
///
public static void Initialize()
{
if (_initialized)
{
return;
}
if (!Directory.Exists(TemplateDirectory))
{
Directory.CreateDirectory(TemplateDirectory);
}
LoadTemplates();
_initialized = true;
}
///
/// Loads templates from disk.
///
private static void LoadTemplates()
{
_templates.Clear();
foreach (var file in Directory.GetFiles(TemplateDirectory, "*.json"))
{
try
{
var template = JsonConvert.DeserializeObject(File.ReadAllText(file));
_templates[template.Name] = template;
}
catch
{
// Ignore invalid template files
}
}
}
///
/// Saves a template to disk.
///
/// The template to save.
private static void SaveTemplate(ProxmoxVMTemplate template)
{
string filePath = Path.Combine(TemplateDirectory, $"{template.Name}.json");
File.WriteAllText(filePath, JsonConvert.SerializeObject(template, Formatting.Indented));
}
///
/// Creates a new template.
///
/// The template to create.
/// The created template.
public static ProxmoxVMTemplate CreateTemplate(ProxmoxVMTemplate template)
{
Initialize();
if (_templates.ContainsKey(template.Name))
{
throw new ArgumentException($"Template with name '{template.Name}' already exists");
}
_templates[template.Name] = template;
SaveTemplate(template);
return template;
}
///
/// Gets a template by name.
///
/// The name of the template.
/// The template.
public static ProxmoxVMTemplate GetTemplate(string name)
{
Initialize();
if (!_templates.TryGetValue(name, out var template))
{
throw new KeyNotFoundException($"Template with name '{name}' not found");
}
return template;
}
///
/// Gets all templates.
///
/// All templates.
public static IEnumerable GetTemplates()
{
Initialize();
return _templates.Values;
}
///
/// Removes a template.
///
/// The name of the template to remove.
public static void RemoveTemplate(string name)
{
Initialize();
if (!_templates.ContainsKey(name))
{
throw new KeyNotFoundException($"Template with name '{name}' not found");
}
_templates.Remove(name);
string filePath = Path.Combine(TemplateDirectory, $"{name}.json");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
///
/// Updates a template.
///
/// The template to update.
/// The updated template.
public static ProxmoxVMTemplate UpdateTemplate(ProxmoxVMTemplate template)
{
Initialize();
if (!_templates.ContainsKey(template.Name))
{
throw new KeyNotFoundException($"Template with name '{template.Name}' not found");
}
_templates[template.Name] = template;
SaveTemplate(template);
return template;
}
}
}