using Innoactive.Portal.AccessControl.Launcher;
using System;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using UnityEngine;

namespace Innoactive.AccessControl
{
    /// <summary>
    /// Checks the Access Control Library integrity for preventing mock implementations.
    /// </summary>
    public static class AccessControlIntegrity
    {
        private const string accessControlIntegrityParametersFilename = "AccessControlIntegrityParameters";

        public static bool CheckAccessControlLibraryIntegrity()
        {
            AccessControlIntegrityParameters integrityParameters = GetAccessControlIntegrityParameters();

            string expectedHash = integrityParameters.sha256Hash;
            string actualHash = GetLibrarySHA256Hash();

            return expectedHash == actualHash;
        }

        public static string GetLibrarySHA256Hash()
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                using (FileStream stream = File.OpenRead(GetLibraryPath()))
                {
                    return BitConverter.ToString(sha256.ComputeHash(stream));
                }
            }
        }

        private static string GetLibraryPath()
        {
            return Assembly.GetAssembly(typeof(LauncherAccessControl)).Location;
        }

        public static AccessControlIntegrityParameters GetAccessControlIntegrityParameters()
        {
            return Resources.Load<AccessControlIntegrityParameters>(accessControlIntegrityParametersFilename);
        }
    }
}
