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

namespace Katteker
{
    /// <summary>
    /// Helps handle the Changelog.
    /// </summary>
    public static class ChangelogHelper
    {
        /// <summary>
        /// Format the Changelog as Html compilant file.s
        /// </summary>
        /// <param name="text"></param>
        /// <param name="extension"></param>
        /// <returns></returns>
        public static string ChangelogAsHtml(this 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 = new MarkdownSharp.Markdown().Transform(text);
                    break;
                default:
                    result = text;
                    break;
            }

            return result;
        }

        /// <summary>
        /// Load changelog from Web or use the local file, if it fails.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static async Task<string> LoadChangelogAsync(string filename, string path)
        {
            if (!string.IsNullOrEmpty(filename) || !string.IsNullOrEmpty(path))
            {
                if (!path.EndsWith("/", StringComparison.Ordinal))
                    path += "/";
                var changelog = await ReadFromRemoteFile(path + filename) ?? ReadFromLocalFile(filename);
                return changelog;
            }

            return null;
        }

        private static async Task<string> ReadFromRemoteFile(string path)
        {
            var webReq = WebRequest.Create(path);
            try
            {
                using (var response = await webReq.GetResponseAsync().ConfigureAwait(false))
                {
                    var responseStream = response.GetResponseStream();
                    if (responseStream == null) return null;
                    using (var sr = new StreamReader(responseStream))
                    {
                        return await sr.ReadToEndAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception)
            {
                // ignore;
            }

            return null;
        }

        private static string ReadFromLocalFile(string filename)
        {
            try
            {
                var changelogFilename = Path.GetFileName(filename);
                if (changelogFilename == null) return null;

                var currentChangelogPath = Path.Combine(Environment.CurrentDirectory, changelogFilename);
                if (File.Exists(currentChangelogPath))
                {
                    return File.ReadAllText(currentChangelogPath);
                }
            }
            catch (Exception)
            {
                // ignore;
            }

            return null;
        }
    }
}