using MediatR;
using NetworkResurrector.Server.PublishedLanguage.Dto;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace NetworkResurrector.Server.Application.Queries
{
    public class GetSystemVersion
    {
        public class Query : IRequest<ServiceVersion> { }

        public class QueryHandler : IRequestHandler<Query, ServiceVersion>
        {
            public QueryHandler()
            {
            }

            public async Task<ServiceVersion> Handle(Query request, CancellationToken cancellationToken)
            {
                var version = Environment.GetEnvironmentVariable("APP_VERSION");
                var appDate = Environment.GetEnvironmentVariable("APP_DATE");

                if (string.IsNullOrEmpty(version))
                    version = Assembly.GetEntryAssembly().GetName().Version.ToString();

                if (!DateTime.TryParse(appDate, out var lastReleaseDate))
                {
                    var location = Assembly.GetExecutingAssembly().Location;
                    lastReleaseDate = File.GetLastWriteTime(location);
                }

                var result = new ServiceVersion(version, lastReleaseDate);
                return await Task.FromResult(result);
            }
        }
    }
}
