using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
using UnityEditor.PackageManager;
using System.Threading.Tasks;
using System;

[InitializeOnLoad]
public class StandardAssetsInitializers : AssetPostprocessor
{

    private static Dictionary<string, string> requiredPackages =
        new Dictionary<string, string>
        {
            {"com.microsoft.mrtk.windowsspeech","USING_MRTK3Speech" },
            {"com.microsoft.mrtk3","TestPP" }
        };

    static StandardAssetsInitializers()
    {

        var currentTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
        var time = PlayerPrefs.GetFloat("time_since_preprocess", -1);
        Debug.Log("Check time since last start");
        Debug.Log(currentTime);
        Debug.Log(time);
        if (currentTime - time > 5)
        {
            Debug.Log("Start Preprocess");
            PlayerPrefs.SetFloat("time_since_preprocess", currentTime);
            StandardAssetsInitializersMethod();
        }
        if(time == -1) PlayerPrefs.SetFloat("time_since_preprocess", currentTime);

    }


    static void StandardAssetsInitializersMethod()
    {

        
        requiredPackages.ToList().ForEach(
            async package =>
            {
                await CheckForPackageAndHandlePreprocessor(package.Key, package.Value);
            }
            );
    }

    static async Task CheckForPackageAndHandlePreprocessor(
        string package, string defineSymbol)
    {
        var targetGroups = (BuildTargetGroup[])Enum.GetValues(typeof(BuildTargetGroup));

        var pack = Client.List();
        while (!pack.IsCompleted) await Task.Delay(100);
        var haveProgrids = pack.Result.FirstOrDefault(q => q.name.Contains(package));

        Debug.Log(package);

        // Add the PP
        if (haveProgrids != null)
        {
            targetGroups.ToList().ForEach(g =>
            {
                string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(g);
                int index = defines.IndexOf(defineSymbol);
                if (index > 0)
                    return;           //this target does not contain the define
                Debug.Log(index);
                if (defines.Length > 0)         //if the list is empty, we don't need to append a semicolon first
                    defines += ";";

                defines += defineSymbol;
                PlayerSettings.SetScriptingDefineSymbolsForGroup(
                g, defines);
            });           

        }

        //Remove the PP
        else
        {
            targetGroups.ToList().ForEach(g =>
            {
                string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(g);
                int index = defines.IndexOf(defineSymbol);
                if (index < 0)
                    return;           //this target does not contain the define
                else if (index > 0)
                    index -= 1;         //include the semicolon before the define
                                        //else we will remove the semicolon after the define

                Debug.Log("Start Remove");
                //Remove the word and it's semicolon, or just the word (if listed last in defines)
                int lengthToRemove = Math.Min(defineSymbol.Length + 1, defines.Length - index);

                //remove the constant and it's associated semicolon (if necessary)
                defines = defines.Remove(index, lengthToRemove);

                PlayerSettings.SetScriptingDefineSymbolsForGroup(g, defines);

            });
        }
    }

}
