/******************************************************************************/
/* SlunkCrypt, by LoRd_MuldeR <MuldeR2@GMX.de>                                */
/* This work has been released under the CC0 1.0 Universal license!           */
/******************************************************************************/

using System;
using System.Reflection;

namespace com.muldersoft.slunkcrypt.gui.utils
{
    static class VersionInfo
    {
        private static readonly Lazy<Version>  m_version       = new Lazy<Version> (InitializeVersion);
        private static readonly Lazy<DateTime> m_buildDateTime = new Lazy<DateTime>(InitializeBuildDateTime);

        // =============================================================================
        // Properties
        // =============================================================================

        public static Version Version { get { return m_version.Value; } }

        public static DateTime BuildDate { get { return m_buildDateTime.Value; } }

        public static new string ToString()
        {
            Version version = m_version.Value;
            return string.Format(
                (version.Revision > 0) ? "Version {0:D}.{1:D}.{2:D}, built on {3}" : "Version {0:D}.{1:D}, built on {3}",
                version.Major, version.Minor, version.Revision, BuildDate.ToString("yyyy-MM-dd"));
        }

        // =============================================================================
        // Internal methods
        // =============================================================================

        private static Version InitializeVersion()
        {
            try
            {
                AssemblyFileVersionAttribute fileVersionAttribute = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyFileVersionAttribute), false) as AssemblyFileVersionAttribute;
                Version fileVersion;
                if (Version.TryParse(fileVersionAttribute?.Version, out fileVersion))
                {
                    return fileVersion;
                }
                else
                {
                    return Assembly.GetExecutingAssembly().GetName().Version;
                }
            }
            catch
            {
                return new Version(0, 0, 0, 0);
            }
        }

        private static DateTime InitializeBuildDateTime()
        {
            try
            {
                Version version = Assembly.GetExecutingAssembly().GetName().Version;
                return new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + TimeSpan.TicksPerSecond * 2 * version.Revision));
            }
            catch
            {
                return new DateTime(1928, 6, 14, 0, 0, 0, DateTimeKind.Utc);
            }
        }
    }
}
