using MediatR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace NetworkResurrector.Api.Application.Queries
{
    public class GetReleaseNotes
    {
        public class Query : IRequest<Model[]>
        {
            public Query() { }
        }

        public record Model(string Version, DateTime Date, string[] Notes);

        public class QueryHandler : IRequestHandler<Query, Model[]>
        {
            public QueryHandler() { }

            public async Task<Model[]> Handle(Query request, CancellationToken cancellationToken)
            {
                var x = Directory.GetCurrentDirectory();
                Console.WriteLine(x);

                var releaseNotes = new XmlDocument();
                releaseNotes.Load("ReleaseNotes.xml");

                var rows = releaseNotes.DocumentElement.SelectNodes("Note");
                var result = new List<Model>();

                foreach (XmlNode node in rows)
                {
                    var version = node.SelectSingleNode("Version").InnerText;
                    var date = GetReleaseDateUtc(node.SelectSingleNode("Date").InnerText);
                    var notes = ParseContent(node.SelectSingleNode("Content").InnerText);

                    result.Add(new Model(version, date, notes));
                }

                return await Task.FromResult(result.ToArray());
            }

            private string[] ParseContent(string text)
            {
                var lines = text
                    .Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None)
                    .Where(z => !string.IsNullOrWhiteSpace(z))
                    .ToArray();

                for (int i = 0; i < lines.Count(); i++)
                {
                    lines[i] = lines[i].TrimStart().TrimEnd();
                }

                return lines;
            }

            private DateTime GetReleaseDateUtc(string date)
            {
                var datetime = Convert.ToDateTime(date);
                var utcDatetime = TimeZoneInfo.ConvertTimeToUtc(datetime, TimeZoneInfo.Local);
                return utcDatetime;
            }
        }
    }
}
