using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditorInternal.VR;
using UnityEditor.SceneManagement;

[ExecuteInEditMode]
public class ManifestManager : MonoBehaviour
{
    public int manifest = 0;
}

[CustomEditor(typeof(ManifestManager))]
[CanEditMultipleObjects]
public class ManifestManagerEditor : Editor
{
    public string[]
        _androidManifest = new string[] { "Daydream", "Oculus" };

    public int
        _manifestIndex = 0;

    private string
        currentManifest,
        androidPluginPath;

    private bool
        fileFound;
    

    void OnEnable()
    {
        androidPluginPath = Application.dataPath + "/Plugins/Android/";
        
    }

    public override void OnInspectorGUI()
    {
        var manifestSwap = target as ManifestManager;

        EditorGUILayout.LabelField("Android Manifest");
        _manifestIndex = EditorGUILayout.Popup(manifestSwap.manifest, _androidManifest);

        if (GUI.changed)
        {
            SetManifest(_manifestIndex);
            EditorUtility.SetDirty(target);
        }
    }


    /// <summary>
    /// This will replace the AndroidManifest.xml file with one of the predefines template manifests.
    /// <!--https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-copy-delete-and-move-files-and-folders-->
    /// </summary>
    /// <param name="index">The Int value of the select dropdown option</param>
    private void SetManifest(int index)
    {
        var manifestSwap = target as ManifestManager;

        string sourceName = "AndroidManifest-" + _androidManifest[index] + ".xml";
        string filePath = Application.dataPath + "/Plugins/Android/";

        // Use Path class to manipulate file and directory paths.
        string sourceFile = Path.Combine(filePath, sourceName);
        string destFile = Path.Combine(filePath, "AndroidManifest.xml");

        if (_androidManifest[index] != currentManifest)
        {
            if (File.Exists(sourceFile))
            {
                // To copy a file to another location and 
                // overwrite the destination file if it already exists.
                File.Copy(sourceFile, destFile, true);
                currentManifest = _androidManifest[index];
                manifestSwap.manifest = index;
            }
            else
            {

                Debug.Log("FILE NOT FOUND: " + sourceFile);
            }
            string[] sdkTargets = VREditor.GetAvailableVirtualRealitySDKs(BuildTargetGroup.Android);


            int numberOfTargets = sdkTargets.Length;
            for (int i = 0; i < numberOfTargets; i++)
            {
                string sdk = sdkTargets[i];
                if (sdk.ToLower() == _androidManifest[index].ToLower())
                {
                    VREditor.SetVirtualRealitySDKs(BuildTargetGroup.Android, new[] { sdk });
                }
            }
        }
    }
    
}