using System;
using System.Reflection;
using Semver;

namespace Katteker
{
    /// <summary>
    /// Utils for the App-Version.
    /// </summary>
    public static class VersionUtils
    {
        /// <summary>
        /// Get the current Version of Application.
        /// </summary>
        public static SemVersion GetCurrentVersion(Assembly assembly = null)
        {
            var a = assembly ?? Assembly.GetEntryAssembly();
            var assemblyVersion = a.GetName().Version.ToString(3);
            var getCurrentVersion = SemVersion.Parse(assemblyVersion);
            var informalVersion = a.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
            if (informalVersion != null && SemVersion.TryParse(informalVersion, out var semVersion))
                return semVersion;
            return getCurrentVersion;
        }

        /// <summary>
        /// Get the System.Version representation of a semantic version.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Version ToSystemVersion(this SemVersion value) => new Version(value.Major, value.Minor, value.Patch, 0);

        /// <summary>
        /// Get the current Version of Application.
        /// </summary>
        public static string GetFullVersion => GetCurrentVersion().ToString();
    }
}