using Katteker.Exceptions;
using Semver;
using System;
using System.Reflection;

namespace Katteker.Utilities
{
    /// <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)
        {
            assembly ??= Assembly.GetEntryAssembly() ?? throw new KattekerUpdateException("No assembly found.");
            var informalVersion = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
                ?.InformationalVersion;
            return informalVersion is not null && SemVersion.TryParse(informalVersion, out var semVersion) ? semVersion : assembly.GetName().Version.ToSemVersion();
        }

        /// <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(value.Major, value.Minor, value.Patch, 0);

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

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