using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace Katteker.Gui
{
    internal static class ChangelogHelper
    {
        private static string GenerateHtmlifyChangelog(string text, string extension)
        {
            string result;
            switch (extension)
            {
                case ".txt":
                    var plainText = WebUtility.HtmlEncode(text);
                    result = plainText.Replace(Environment.NewLine, "<br />");
                    break;
                case ".md":
                    result = CommonMark.CommonMarkConverter.Convert(text);
                    break;
                default:
                    result = text;
                    break;
            }

            return result;
        }

        internal static async Task<string> LoadChangelogAsync(string filename, string path)
        {
            if (!string.IsNullOrEmpty(filename) || !string.IsNullOrEmpty(path))
            {
                if (!path.EndsWith("/", StringComparison.Ordinal))
                    path += "/";
                var webReq = WebRequest.Create(path + filename);
                try
                {
                    using (var response = await webReq.GetResponseAsync().ConfigureAwait(false))
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        return GenerateHtmlifyChangelog(await sr.ReadToEndAsync().ConfigureAwait(false),
                            Path.GetExtension(filename));
                    }
                }
                catch (WebException)
                {
                    var changelogFilename = Path.GetFileName(filename);
                    if (changelogFilename == null) return GenerateHtmlifyChangelog("Changelog not found", ".txt");
                    var currentChangelogPath = Path.Combine(Environment.CurrentDirectory, changelogFilename);
                    if (File.Exists(currentChangelogPath))
                    {
                        return GenerateHtmlifyChangelog(File.ReadAllText(currentChangelogPath), Path.GetExtension(filename));
                    }
                }
            }

            return GenerateHtmlifyChangelog("Changelog not found", ".txt");
        }
    }
}