using System;
using System.Collections.Generic;
using System.IO;
using Avalonia.Markup.Xaml.Templates;

namespace SessionZero.Data;

public class Datapack
{
    public DatapackMetadata Metadata { get; set; }

    private readonly string _path;
    private Dictionary<string, Dataset> _datasetLookup = [];
    private Dictionary<string, SzTemplate> _templateLookup = [];
    

    public Datapack(string name, string id, string version = "1.0.0", string[]? compatibleSystems = null, string description = "")
    {
        Metadata = new()
        {
            Name = name,
            Id = id,
            Version = version,
            CompatibleSystems = compatibleSystems,
            Description = description,
            Uuid = Guid.NewGuid().ToString()
        };
        
        _path = Path.Combine(AppManager.DatapacksDirectory, Metadata.Id);
    }
    
    public void Save()
    {

        if (!Directory.Exists(_path))
        {
            Directory.CreateDirectory(_path);
            Directory.CreateDirectory($"{_path}/resources");
            Directory.CreateDirectory($"{_path}/datasets");
            Directory.CreateDirectory($"{_path}/templates");
        }

        if (!File.Exists($"{_path}/datapack.meta"))
        {
            File.WriteAllText($"{_path}/datapack.meta", Metadata.ToString());
        }
    }

    public void AddDataset(Dataset dataset)
    {
        dataset.Save($"{_path}/datasets/");
        _datasetLookup.TryAdd(dataset.Metadata.Id, dataset);
    }

    public void AddTemplate(SzTemplate template)
    {
        var success = _templateLookup.TryAdd(template.Id, template);
        if (success)
        {
            File.WriteAllText($"{_path}/templates/{template.Id}.sztl", template.SztlText);
        }
    }
}