using MediatR;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace NetworkResurrector.Agent.Application.Queries
{
    public class GetSystemVersion
    {
        public class Query : IRequest<Model> { }

        public record Model(string Version, DateTime LastUpdateDate);

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

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

                if (string.IsNullOrEmpty(version))
                    version = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;

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

                var result = new Model(version, lastUpdateDate);
                return await Task.FromResult(result);
            }
        }
    }
}
