﻿using System.Linq;
using VMLab.Exceptions;
using VMLab.Helpers;

namespace VMLab.Startup
{
    public class SelectHypervisor : IStartup
    {
        private readonly IConfig _config;
        private readonly IConsole _console;
        private readonly IEnvironmentHelper _environmentHelper;

        public SelectHypervisor(IConfig config, IConsole console, IEnvironmentHelper environmentHelper)
        {
            _config = config;
            _console = console;
            _environmentHelper = environmentHelper;
        }

        public int Priority => 10;
        public void Execute()
        {
            var hypervisor = _config.All(ConfigScope.Dynamic).Where(h => h.Key.StartsWith("hypervisor_present"))
                .Select(h => h.Value).FirstOrDefault();

            var hyprevisorPath = _config.Get(ConfigScope.Dynamic, $"{hypervisor}_path");

            if (string.IsNullOrEmpty(hypervisor))
            {
                _console.Error("Can't find a hypervisor on this system!");
                throw new TerminalReportedApplicationException();
            }

            _config.Set(ConfigScope.Dynamic, "Hypervisor", hypervisor);

            if (string.IsNullOrEmpty(hyprevisorPath)) return;

            var path = $"{_environmentHelper.Var("path")};{hyprevisorPath}";
            _environmentHelper.SetVar("path", path);
        }
    }
}
