using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using MaxLib.WebServer;

namespace Dacryptero.Web;

public static class Tools
{
    public static async Task<bool> AddTemplate(WebProgressTask task,
        string templateName, Dictionary<string, string>? vars = null
    )
    {
        var path = Path.Combine(Config.Default.Server.TemplateDir, templateName);
        if (!File.Exists(path))
        {
            task.Response.StatusCode = HttpStateCode.InternalServerError;
            task.Document.DataSources.Add(new HttpStringDataSource(
                $"template {templateName} not found"
            ));
            return false;
        }

        var template = new StringBuilder(
            await File.ReadAllTextAsync(path)
                .ConfigureAwait(false)
        );

        if (vars != null)
            foreach (var (key, value) in vars)
                template.Replace($"<!--I:{key.ToUpper()}-->", value);
        
        task.Document.DataSources.Add(new HttpStringDataSource(template.ToString())
        {
            MimeType = MimeType.TextHtml,
        });
        return true;
    }
}