﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Onward.CustomContent
{
    public static class Util
    {
        public static void RenderDownwardsLine(Vector3 pos)
        {
            RaycastHit rayHit;
            if (Physics.Raycast(pos, -Vector3.up, out rayHit, 1f))
            {
                Gizmos.color = Color.blue;

                Gizmos.DrawLine(pos, rayHit.point);
                Gizmos.DrawWireSphere(rayHit.point, 0.05f);
            }
        }

        public static bool EnforceSingleInstance<T>() where T : MonoBehaviour
        {
#if UNITY_EDITOR
            T[] otherInstances = GameObject.FindObjectsOfType<T>();

            if (otherInstances.Length > 1)
            {
                Debug.Log("Only one instance allowed, destroying.");

                otherInstances[0].gameObject.SetActive(false);

                Object.DestroyImmediate(otherInstances[0].gameObject);

                return false;
            }

            return true;
#else
            return true;
#endif
        }

#if UNITY_EDITOR
        public static void StartBackgroundTask(IEnumerator update, System.Action end = null)
        {
            UnityEditor.EditorApplication.CallbackFunction closureCallback = null;

            closureCallback = () =>
            {
                try
                {
                    if (update.MoveNext() == false)
                    {
                        if (end != null)
                            end();
                        UnityEditor.EditorApplication.update -= closureCallback;
                    }
                }
                catch (System.Exception ex)
                {
                    if (end != null)
                        end();
                    Debug.LogException(ex);
                    UnityEditor.EditorApplication.update -= closureCallback;
                }
            };

            UnityEditor.EditorApplication.update += closureCallback;
        }

        public static string CalculateMD5HashBase64(byte[] bytes)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();

            byte[] hash = md5.ComputeHash(bytes);

            return System.Convert.ToBase64String(hash);
        }
#endif
    }
}
