using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Linq;

#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.PackageManager;
#endif

namespace SimpleARPro
{
#if UNITY_EDITOR

    [InitializeOnLoad]
    public static class SimpleARInitializer
    {

#if UNITY_2021_1_OR_NEWER
        private static bool LoadState
        {
            get
            {
                return bool.Parse(
                    PlayerPrefs.GetString("LoadState",
                    false.ToString())
                    );
            }
            set
            {
                PlayerPrefs.SetString("LoadState",
                    value.ToString());
            }
        }
#endif

        static SimpleARInitializer()
        {
#if UNITY_2021_1_OR_NEWER
            //ForceLoad();
            DeleteVersionControl();
#endif
        }

#if UNITY_2021_1_OR_NEWER

        [MenuItem("SimpleAR Pro/Utilities/Force Launch", false, 100)]
        public static void ForceLoad()
        {
            bool loaded = LoadState;
            if (!loaded)
            {
                DeleteCorePackageInitializer();
                UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation();
            }            
            LoadState = true;
        }

        [InitializeOnLoadMethod]
        private static void DeleteVersionControl()
        {
#if UNITY_2020_1_OR_NEWER
            Client.Remove("com.unity.collab-proxy");
#endif
        }



        [InitializeOnLoadMethod]
        private static void DeleteCorePackageInitializer()
        {
            try
            {
                var libraryPath = Application.dataPath;
                string packageCacheRelPath = "Library/PackageCache";
                string fullPackageCachePath = libraryPath.Replace("Assets", packageCacheRelPath);
                var subDirs = Directory.GetDirectories(fullPackageCachePath);
                string coreServicesPath = subDirs.ToList().Where(path => path.Contains("com.unity.services.core")).FirstOrDefault();
                coreServicesPath += "\\Runtime\\Registration";
                var files = Directory.GetFiles(coreServicesPath);
                string initFilePath = files.Where(fileName => fileName.Contains("CorePackageInitializer")).First();
                if (initFilePath != null) File.Delete(initFilePath);

            }
            catch (System.Exception e) { Debug.Log(e); }
        }
#endif


    }

#endif

}