﻿using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Net;
using System.Threading;
using UtopiaVRUploader;
using UnityEditor.Experimental.SceneManagement;
using System.Collections;
using System.Threading.Tasks;
using UnityEditor.SceneManagement;

//using Unity.EditorCoroutines.Editor;

public class utopiavruploader : EditorWindow
{
    // Class Enum
    private static class Platforms
    {
        public static string Windows = "1";
        public static string Android = "2";
        public static string All = "3";
    }

    public uvrloader uvrcntrl = new uvrloader();

    bool isandroid = true;
    bool iswindow = true;
    //bool iswindow = false;
    string envirname = "name";
    string username = "";
    string password = "";
    int lastnameselected = 0;
    int _selected = 0;
    bool firsttime = true;
    bool worldsetup = false;
    bool worldlock = false;
    public Material spawn;
    public Material northwall;
    public Material southwall;
    public Material easewall;
    public Material westwall;

    [MenuItem("UtopiaVR/Utopiavruploader")]
    public static void showwindow()
    {
        //Rect R = GetanonymousainGameView().position;
        //R.width = 800;
        //R.height = 600;
        //GetanonymousainGameView().position = R;
        //GetWindow<ConversationsEditorWindow>().position = new Rect(x, y, width, height);

        GetWindow<utopiavruploader>("UtopiaVR Uploader").position = new Rect(0, 0, 400, 600);
    }

    // Returns the resolution of the window
    public static EditorWindow GetanonymousainGameView()
    {
        System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor");
        System.Reflection.MethodInfo GetSizeOfMainGameView = T.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
        System.Object Res = GetSizeOfMainGameView.Invoke(null, null);
        return (EditorWindow)Res;
    }

    //private FtpClient Client { get; }
    private void OnGUI()
    {
        //Debug.Log("this is the current scene that is open : " + EditorSceneManager.GetActiveScene().path);
        //scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width(800), GUILayout.Height(800));
        //string localpathunity = System.IO.Directory.GetCurrentDirectory();
        string[] allPaths = Directory.GetFiles(Application.dataPath, "utopiavrlogo.png", SearchOption.AllDirectories);

        //string filename = localpathunity + "utopiavrlogo.png";
        var rawData = System.IO.File.ReadAllBytes(allPaths[0]);
        Texture2D tex = new Texture2D(2, 2); // Create an empty Texture; size doesn't matter (she said)
        tex.LoadImage(rawData);
        //Texture fish = (Texture)Resources.Load("utopiavrlogo.png");


        GUI.DrawTexture(new Rect(0, 0, 100, 100), tex);
        GUILayout.Space(110);

        GUILayout.Label("Upload Worlds", EditorStyles.boldLabel);
        if (uvrcntrl.loggedin == false)
        {
            loginGUI();
        }
        else
        {
            uploaderGUI();
        }

    }

    // GUI elements for users to log in
    private void loginGUI()
    {
        username = EditorGUILayout.TextField("Username Name: ", username);
        password = EditorGUILayout.TextField("Password Name: ", password);
        if (GUILayout.Button("log in"))
        {
            uvrcntrl.UVRlogin(username, password);
        }
    }


    // GUI elements for uploading UVR world
    private void uploaderGUI()
    {
        //Debug.Log("LOGGED IN");

        //setup spawn point button
        // GameObject savedgo = new GameObject(); 
        //if (GameObject.Find("uvrenvironment").transform.Find("utopianspawnpoint") != null)
        if (GameObject.Find("uvrenvironment") != null)
        {
            if (GameObject.Find("uvrenvironment").transform.Find("utopianspawnpoint") != null)
            {
                worldsetup = true;
                //check to make sure all the the objects are under environment and call cameras are gone
                //delete cameras
                Camera[] allCameras = FindObjectsOfType<Camera>();
                foreach (Camera c in Camera.allCameras)
                {
                    DestroyImmediate(c.gameObject);
                }


                //check if the environment was already  done
                GameObject uEnviroment;
                if (GameObject.Find("uvrenvironment") == null)
                {
                    //make a gameobject named environment
                    uEnviroment = new GameObject();
                    uEnviroment.name = "uvrenvironment";

                }
                else
                {
                    uEnviroment = GameObject.Find("uvrenvironment");
                }
                //make all the other gameobjects childern of environment
                //savedgo = go1;
                foreach (GameObject element in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects())
                {
                    if (element.name != "uvrenvironment")
                        element.transform.SetParent(uEnviroment.transform);

                    if (element.GetComponent<MeshFilter>() != null)
                    {
                        var meshFilter = element.GetComponent<MeshFilter>();
                        var mesh = meshFilter.sharedMesh;
                        //Debug.Log(mesh.name);
                        string str = mesh.name;
                        //Debug.Log("SEARCHING probuilder items filter: " + str + " name of object: " + g.name);
                        //added this for probudiler users
                        int at1 = -1;
                        at1 = str.IndexOf("pb_", 0, str.Length);
                        if (at1 != -1)
                        {
                            //found them they are here now
                            Debug.Log("Found probuilder items filter: " + str + " name of object: " + element.name);
                            Mesh newmesh = new Mesh();
                            newmesh = mesh;
                            newmesh.name = element.name + "newmesh";
                            //string path = EditorUtility.SaveFilePanel("Save Separate Mesh Asset", "Assets/", name, "asset");
                            AssetDatabase.CreateAsset(newmesh, "Assets/Prefabs/" + newmesh.name + ".asset");
                            AssetDatabase.SaveAssets();
                        }
                    }
                }

            }

        }

        if (worldsetup == false)
        {

            GUILayout.Label("This is add a object uvrenvironment and put all the other objects in it.  ", EditorStyles.wordWrappedLabel);
            GUILayout.Label("It will also create a spawn point for you to move to where you want to the utopian to sqawn at; before you do locksetup", EditorStyles.wordWrappedLabel);
            GUILayout.Label("", EditorStyles.wordWrappedLabel);

            if (GUILayout.Button("setupworld"))
            {
                //delete cameras
                Camera[] allCameras = FindObjectsOfType<Camera>();
                foreach (Camera c in Camera.allCameras)
                {
                    DestroyImmediate(c.gameObject);
                }
                //check if the environment was already  done
                GameObject go1;
                if (GameObject.Find("uvrenvironment") == null)
                {
                    //make a gameobject named environment
                    go1 = new GameObject();
                    go1.name = "uvrenvironment";

                }
                else
                {
                    go1 = GameObject.Find("uvrenvironment");
                }
                //make all the other gameobjects childern of environment
                //savedgo = go1;
                foreach (GameObject g in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects())
                {
                    if (g.name != "uvrenvironment")
                        g.transform.SetParent(go1.transform);
                    if (g.GetComponent<MeshFilter>() != null)
                    {
                        var meshFilter = g.GetComponent<MeshFilter>();
                        var mesh = meshFilter.sharedMesh;
                        //Debug.Log(mesh.name);
                        string str = mesh.name;
                        //Debug.Log("SEARCHING probuilder items filter: " + str + " name of object: " + g.name);
                        //added this for probudiler users
                        int at2 = -1;
                        at2 = str.IndexOf("pb_", 0, str.Length);
                        if (at2 != -1)
                        {
                            //found them they are here now
                            Debug.Log("Found probuilder items filter: " + str + " name of object: " + g.name);
                            Mesh newmesh = new Mesh();
                            newmesh = mesh;
                            newmesh.name = g.name + "newmesh";
                            //string path = EditorUtility.SaveFilePanel("Save Separate Mesh Asset", "Assets/", name, "asset");
                            AssetDatabase.CreateAsset(newmesh, "Assets/Prefabs/" + newmesh.name + ".asset");
                            AssetDatabase.SaveAssets();
                        }
                    }

                }


                string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;

                string combinePath = Path.Combine(currentDirectory, "Assets"); ;


                // Replace "YourScriptName" with the actual name of your script
                string[] scriptGUIDs = AssetDatabase.FindAssets("utopiavruploader");
                if (scriptGUIDs.Length > 0)
                {
                    // Get the path of the first asset that matches the script name
                    string scriptPath = AssetDatabase.GUIDToAssetPath(scriptGUIDs[0]);
                    var directoryPath = Path.GetDirectoryName(scriptPath);
                    Debug.Log("Script Directory: " + directoryPath);
                    combinePath = directoryPath;
                }
                else
                {
                    Debug.LogError("Script not found.");
                }
                //combinePath = Path.Combine(currentDirectory, "Assets"); ;
                combinePath = combinePath + "\\" + "Assets";
                GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                //cube.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath("Assets/Plugins/utopiavrloader/spawnpoint.mat", typeof(Material));
                cube.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/spawnpoint.mat", typeof(Material));
                cube.name = "utopianspawnpoint";
                cube.transform.position = new Vector3(0, 0, 0);
                cube.transform.localScale = new Vector3(1, 2, 1);
                cube.GetComponent<BoxCollider>().enabled = false;
                cube.transform.SetParent(go1.transform);
                //north portal
                GameObject cubenorth = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubenorth.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/northwall.mat", typeof(Material));
                cubenorth.name = "utopiannorthwall";
                cubenorth.transform.position = new Vector3(0, 0, 0);
                cubenorth.transform.localScale = new Vector3(250, 100, 5);
                //cubenorth.GetComponent<MeshRenderer>().materials[0] = 
                cubenorth.transform.SetParent(go1.transform);
                //north portal spawn
                GameObject cubenorths = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubenorths.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/spawnpoint.mat", typeof(Material));
                cubenorths.name = "utopianspawnpointN";
                cubenorths.transform.position = new Vector3(0, 0, 0);
                cubenorths.transform.localScale = new Vector3(1, 2, 1);
                //cubenorth.GetComponent<MeshRenderer>().materials[0] = 
                cubenorths.GetComponent<BoxCollider>().enabled = false;
                cubenorths.transform.SetParent(go1.transform);
                //south portal
                GameObject cubesouth = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubesouth.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/south wall.mat", typeof(Material));
                cubesouth.name = "utopiansouthwall";
                cubesouth.transform.position = new Vector3(0, 0, 249);
                cubesouth.transform.localScale = new Vector3(250, 100, 5);
                //cubenorth.GetComponent<MeshRenderer>().materials[0] = 
                cubesouth.transform.SetParent(go1.transform);
                //south portal spawn
                GameObject cubesouths = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubesouths.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/spawnpoint.mat", typeof(Material));
                cubesouths.name = "utopianspawnpointS";
                cubesouths.transform.position = new Vector3(0, 0, 249);
                cubesouths.transform.localScale = new Vector3(1, 2, 1);
                //cubenorth.GetComponent<MeshRenderer>().materials[0] = 
                cubesouths.GetComponent<BoxCollider>().enabled = false;
                cubesouths.transform.SetParent(go1.transform);
                //west portal
                GameObject cubewest = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubewest.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/west wall.mat", typeof(Material));
                cubewest.name = "utopianwestwall";

                cubewest.transform.Rotate(0, 90, 0);
                cubewest.transform.position = new Vector3(124.8F, 0, 126.7F);
                cubewest.transform.localScale = new Vector3(250, 100, 5);
                //cubewest.transform.position = new Vector3(-124.8F, 0, 126.7F);
                //cubewest.transform.localScale = new Vector3(250, 100, 5);
                //cubewest.GetComponent<MeshRenderer>().materials[0] = 
                cubewest.transform.SetParent(go1.transform);
                //west portal spawn
                GameObject cubewests = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubewests.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/spawnpoint.mat", typeof(Material));
                cubewests.name = "utopianspawnpointW";
                cubewests.transform.position = new Vector3(124.8F, 0, 126.7F);
                cubewests.transform.localScale = new Vector3(1, 2, 1);
                //cubenorth.GetComponent<MeshRenderer>().materials[0] = 
                cubewests.GetComponent<BoxCollider>().enabled = false;
                cubewests.transform.SetParent(go1.transform);
                //east portal
                GameObject cubeeast = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubeeast.name = "utopianeastwall";
                cubeeast.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/east wall.mat", typeof(Material));

                cubeeast.transform.Rotate(0, 90, 0);
                cubeeast.transform.position = new Vector3(-124.8F, 0, 126.7F);
                cubeeast.transform.localScale = new Vector3(250, 100, 5);
                ///cubeeast.transform.position = new Vector3(124.8F, 0, 126.7F);
                //cubeeast.transform.localScale = new Vector3(250, 100, 5);
                //cubeeast.GetComponent<MeshRenderer>().materials[0] = 
                cubeeast.transform.SetParent(go1.transform);
                //east portal spawn
                GameObject cubeeasts = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubeeasts.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(combinePath + "/spawnpoint.mat", typeof(Material));
                cubeeasts.name = "utopianspawnpointE";
                cubeeasts.transform.position = new Vector3(-124.8F, 0, 126.7F);
                cubeeasts.transform.localScale = new Vector3(1, 2, 1);
                //cubenorth.GetComponent<MeshRenderer>().materials[0] = 
                cubeeasts.GetComponent<BoxCollider>().enabled = false;
                cubeeasts.transform.SetParent(go1.transform);
                //utopian skybox
                GameObject cubeskybox = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cubeskybox.name = "utopianskybox";
                //cubeskybox.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(curpath + "/east wall.mat", typeof(Material));

                cubeskybox.transform.Rotate(0, 90, 0);
                cubeskybox.transform.position = new Vector3(0, 0, 0);
                cubeskybox.transform.localScale = new Vector3(1, 1, 1);
                Material mats = new Material(RenderSettings.skybox);
                cubeskybox.GetComponent<Renderer>().material = mats;
                cubeskybox.GetComponent<Renderer>().enabled = false;
                cubeskybox.transform.SetParent(go1.transform);
                worldsetup = true;
            }


        }
        if (worldlock == false && worldsetup == true)
        {
            GUILayout.Label("STEPS", EditorStyles.wordWrappedLabel);
            GUILayout.Label("1. Look for spawnpoint", EditorStyles.wordWrappedLabel);
            GUILayout.Label("  1a. Click spawnpoint", EditorStyles.wordWrappedLabel);
            GUILayout.Label("  1b. Move spawnpoint where you want the Utopian to spawn at", EditorStyles.wordWrappedLabel);
            GUILayout.Label("2. Look for each walls north, south, East, and West", EditorStyles.wordWrappedLabel);
            GUILayout.Label("  2a. Click on each and move them where you want them (these are so your other sectors can be linked in the world to allow Utopian to travel.)", EditorStyles.wordWrappedLabel);
            GUILayout.Label("     2.a.1. Optional rotate, and/or rescale your walls for smaller sectors or interior scenes.  ", EditorStyles.wordWrappedLabel);
            GUILayout.Label("     2.a.2. Optional you can delete any or all the walls but remember the Utopian can not jump to the connected sector of the world if you do that.  ", EditorStyles.wordWrappedLabel);
            GUILayout.Label("Our world building is set by universe to worlds to sectors of those worlds.  So Utopians and walk from one sector to the next and explore you whole universe", EditorStyles.wordWrappedLabel);
            GameObject.Find("uvrenvironment").transform.Find("utopianspawnpoint").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GameObject.Find("utopiannorthwall") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopiannorthwall").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GameObject.Find("utopiansouthwall") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopiansouthwall").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GameObject.Find("utopianwestwall") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopianwestwall").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GameObject.Find("utopianeastwall") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopianeastwall").gameObject.GetComponent<MeshRenderer>().enabled = true;
            //turning off the render for all the new spawn points.
            if (GameObject.Find("utopianspawnpointN") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointN").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GameObject.Find("utopianspawnpointS") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointS").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GameObject.Find("utopianspawnpointE") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointE").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GameObject.Find("utopianspawnpointW") != null)
                GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointW").gameObject.GetComponent<MeshRenderer>().enabled = true;
            if (GUILayout.Button("Lock in world"))
            {
                worldlock = true;
                GameObject.Find("uvrenvironment").transform.Find("utopianspawnpoint").gameObject.GetComponent<MeshRenderer>().enabled = false;
                if (GameObject.Find("utopiannorthwall") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopiannorthwall").gameObject.GetComponent<MeshRenderer>().enabled = false;
                if (GameObject.Find("utopiansouthwall") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopiansouthwall").gameObject.GetComponent<MeshRenderer>().enabled = false;
                if (GameObject.Find("utopianwestwall") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopianwestwall").gameObject.GetComponent<MeshRenderer>().enabled = false;
                if (GameObject.Find("utopianeastwall") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopianeastwall").gameObject.GetComponent<MeshRenderer>().enabled = false;
                //turning off the render for all the new spawn points.
                if (GameObject.Find("utopianspawnpointN") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointN").gameObject.GetComponent<MeshRenderer>().enabled = false;
                if (GameObject.Find("utopianspawnpointS") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointS").gameObject.GetComponent<MeshRenderer>().enabled = false;
                if (GameObject.Find("utopianspawnpointE") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointE").gameObject.GetComponent<MeshRenderer>().enabled = false;
                if (GameObject.Find("utopianspawnpointW") != null)
                    GameObject.Find("uvrenvironment").transform.Find("utopianspawnpointW").gameObject.GetComponent<MeshRenderer>().enabled = false;

            }

        }


        // setup the drop down 
        if (worldlock == true && worldsetup == true)
        {
            _selected = EditorGUILayout.Popup("My Simple Dropdown", _selected, uvrcntrl.environmentname);

            if (firsttime)
            {
                envirname = uvrcntrl.environmentname[_selected];
                Debug.Log("Currently the " + envirname + " Environment is set to add this scene too");
                firsttime = false;
            }
            if (lastnameselected != _selected)
            {
                envirname = uvrcntrl.environmentname[_selected];
                Debug.Log("Currently the " + envirname + " Environment is set to add this scene too");
                lastnameselected = _selected;
            }
            //envirname = EditorGUILayout.TextField("Environment Name: ", envirname);
            isandroid = GUILayout.Toggle(isandroid, " Android");
            iswindow = GUILayout.Toggle(iswindow, " Windows");
            if (GUILayout.Button("Build and Upload"))
            {

                //delete cameras
                Camera[] allCameras = FindObjectsOfType<Camera>();
                foreach (Camera c in Camera.allCameras)
                {
                    DestroyImmediate(c.gameObject);
                }
                //check if the environment was already  done
                GameObject go1;
                if (GameObject.Find("uvrenvironment") == null)
                {
                    //make a gameobject named environment
                    go1 = new GameObject();
                    go1.name = "uvrenvironment";

                }
                else
                {
                    go1 = GameObject.Find("uvrenvironment");
                }
                //check if the skybox is saved was already  done
                if (GameObject.Find("utopianskybox") == null)
                {
                    //utopian skybox
                    GameObject cubeskybox = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cubeskybox.name = "utopianskybox";
                    //cubeskybox.GetComponent<Renderer>().material = (Material)AssetDatabase.LoadAssetAtPath(curpath + "/east wall.mat", typeof(Material));

                    cubeskybox.transform.Rotate(0, 90, 0);
                    cubeskybox.transform.position = new Vector3(0, 0, 0);
                    cubeskybox.transform.localScale = new Vector3(1, 1, 1);
                    Material mats = new Material(RenderSettings.skybox);
                    cubeskybox.GetComponent<Renderer>().material = mats;
                    cubeskybox.GetComponent<Renderer>().enabled = false;
                    cubeskybox.transform.SetParent(go1.transform);

                }
                //make all the other gameobjects childern of environment

                foreach (GameObject g in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects())
                {
                    if (g.name != "uvrenvironment")
                        g.transform.SetParent(go1.transform);
                    //added this for probudiler users
                    if (g.GetComponent<MeshFilter>() != null)
                    {
                        var meshFilter = g.GetComponent<MeshFilter>();
                        var mesh = meshFilter.sharedMesh;
                        //Debug.Log(mesh.name);
                        string str = mesh.name;
                        //Debug.Log("SEARCHING probuilder items filter: " + str + " name of object: " + g.name);
                        int at1 = -1;
                        at1 = str.IndexOf("pb_", 0, str.Length);
                        if (at1 != -1)
                        {
                            //found them they are here now
                            Debug.Log("Found probuilder items filter: " + str + " name of object: " + g.name);
                            Mesh newmesh = new Mesh();
                            newmesh = mesh;
                            newmesh.name = g.name + "newmesh";
                            //string path = EditorUtility.SaveFilePanel("Save Separate Mesh Asset", "Assets/", name, "asset");
                            AssetDatabase.CreateAsset(newmesh, "Assets/Prefabs/" + newmesh.name + ".asset");
                            AssetDatabase.SaveAssets();
                        }

                    }
                }

                buildAndUpload(envirname, go1);


            }

        }

    }


    static IEnumerator IEDelayEditor(string envirname, GameObject go1)
    {
        Debug.Log("Wait 1 second");
        AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
        buildMap[0].assetBundleName = envirname;
        string[] evirAssets = new string[1];
        evirAssets[0] = "Assets/Prefabs2/" + go1.name + ".prefab";
        buildMap[0].assetNames = evirAssets;
        if (!AssetDatabase.IsValidFolder("Assets/ABs/win"))
        {
            if (!AssetDatabase.IsValidFolder("Assets/ABs"))
                AssetDatabase.CreateFolder("Assets", "ABs");
            AssetDatabase.CreateFolder("Assets/ABs", "win");
        }
        Debug.Log("Starting Window build ");

        yield return BuildPipeline.BuildAssetBundles("Assets/ABs/win/", buildMap, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
        Debug.Log("After 1 second");
    }
    async void buildAndUpload(string envirName, GameObject go1)
    {
        if (!iswindow && !isandroid)
        {
            throw new Exception("Building for unspecified platform");
        }

        //build prefab
        await customPrefadbBuild(envirName, go1);
        //build asset window
        if (iswindow)
        {
            await windowAssBuild(envirName, go1);

        }
        //build asset android
        if (isandroid)
        {
            await androidAssBuild(envirName, go1);

        }


        string localPathUnity = System.IO.Directory.GetCurrentDirectory();

        //upload asset android
        string initialPath = Platforms.Android;
        if (isandroid && iswindow)
        {
            initialPath = Platforms.All;
        }
        else if (isandroid)
        {
            initialPath = Platforms.Android;
        }
        else if (iswindow)
        {
            // Upload asset window
            initialPath = Platforms.Windows;
        }
        else throw new InvalidOperationException("Unexpected combination of platform flags.");
        string filepath = localPathUnity + @"\Assets\ABs\";
        uvrcntrl.UVRUpload(envirName, initialPath, filepath);


    }

    // Save world as prefab
    async static Task customPrefadbBuild(string envirName, GameObject go1)
    {
        // Debug for prefab
        Debug.Log("Waiting prefab...");
        Debug.Log("Waiting prefab envirname: " + envirName);
        Debug.Log("Waiting prefab go1: " + go1.name);

        // Create path variable
        string localkpath = "Assets/Resources/" + go1.name + ".prefab";

        // Create and wipe folder
        clensResourceFolder();
        //if already maded delete

        //
        //UnityEngine.Object Prefab = Instantiate(Resources.Load(go1.name) as GameObject);
        //Prefab.name = go1.name;
        //Debug.Log("name of a prefab instant: " + Prefab.name);
        //DestroyImmediate(Prefab, true);

        //Debug.Log("name of a prefab deleted?: " + AssetDatabase.DeleteAsset(localkpath));

        // Generate the path
        localkpath = AssetDatabase.GenerateUniqueAssetPath(localkpath);

        // Save Object as prefab in folder
        PrefabUtility.SaveAsPrefabAsset(go1, localkpath);
        await Task.Yield();
        Debug.Log("done prefab...");
    }



    // Windows Bundle Creator
    async static Task windowAssBuild(string envirName, GameObject go1)
    {
        // Create and fill basic bundle information
        Debug.Log("Starting Window build ");
        AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
        buildMap[0].assetBundleName = envirName;
        string[] evirAssets = new string[1];
        /* old way
        evirAssets[0] = "Assets/Resources/" + go1.name + ".prefab";
        //adding the skybox in the zone
        Material mats = new Material(RenderSettings.skybox);
        //GetComponent<Renderer>().material.CopyPropertiesFromMaterial(RenderSettings.skybox);
        mats.name = envirname + "_skybox.mat";
        AssetDatabase.GetAssetPath(mats);
        AssetDatabase.CreateAsset(mats, AssetDatabase.GenerateUniqueAssetPath("Assets/Resources/" + envirname + "_skybox.mat"));
        evirAssets[1] = "Assets/Resources/" + envirname + "_skybox.mat";
        */
        //string[] levels = new string[] { "Assets/Level1.unity" };
        //EditorSceneManager.GetActiveScene().nam        ;
        evirAssets[0] = EditorSceneManager.GetActiveScene().path;
        Debug.Log("path of the windows scene: " + EditorSceneManager.GetActiveScene().path);

        // Get the currently active scene
        //Scene currentScene = EditorSceneManager.GetActiveScene();

        // Check if the scene has unsaved changes
        if (EditorSceneManager.GetActiveScene().isDirty)
        {
            // Save the changes to the current scene
            EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());
        }
        //BuildPipeline.BuildStreamedSceneAssetBundle(levels, "Streamed-Level1.unity3d", BuildTarget.StandaloneWindows);

        buildMap[0].assetNames = evirAssets;

        // Create folders if they dont exist
        validateOutputPaths();


        Debug.Log("buildmap assetnames numbers: " + buildMap[0].assetNames.Length);
        foreach (string eachitem in buildMap[0].assetNames)
        {
            Debug.Log("eachitem  is:" + eachitem);

        }

        // Create asset bundle in designated folder
        //BuildPipeline.BuildStreamedSceneAssetBundle(evirAssets, "Assets/ABs/win/"+ envirname, BuildTarget.StandaloneWindows64);
        BuildPipeline.BuildAssetBundles("Assets/ABs/win/", buildMap, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
        await Task.Yield();
        Debug.Log("After Window build ");
    }

    // Android Bundle Creator
    async static Task androidAssBuild(string envirName, GameObject go1)
    {
        // Create and fill basic bundle information
        Debug.Log("Creating Android Build ");
        AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
        buildMap[0].assetBundleName = envirName;
        string[] evirAssets = new string[1];
        evirAssets[0] = EditorSceneManager.GetActiveScene().path;
        Debug.Log("Path of the windows scene: " + EditorSceneManager.GetActiveScene().path);

        // Get the currently active scene
        //Scene currentScene = EditorSceneManager.GetActiveScene();

        // Check if the scene has unsaved changes
        if (EditorSceneManager.GetActiveScene().isDirty)
        {
            // Save the changes to the current scene
            EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());
        }
        //BuildPipeline.BuildStreamedSceneAssetBundle(levels, "Streamed-Level1.unity3d", BuildTarget.StandaloneWindows);

        // Populate assetNames
        buildMap[0].assetNames = evirAssets;

        //old way
        /*
        Material testit = Resources.Load("Assets/Resources/" + envirname + "_skybox.mat", typeof(Material)) as Material;
        if (testit != null)
        {
            Debug.Log("mt found one testit:" + testit);
            //Place the lightmap data here
            LightingDataAsset templights = Lightmapping.lightingDataAsset;
            if (templights != null)
            {
                string[] evirAssets = new string[3];
                evirAssets[0] = "Assets/Resources/" + go1.name + ".prefab";
                evirAssets[1] = "Assets/Resources/" + envirname + "_skybox.mat";

                string assetPath = AssetDatabase.GetAssetPath(templights);
                Debug.Log("light path sky/light assetPath:" + assetPath);
                evirAssets[2] = assetPath;
                buildMap[0].assetNames = evirAssets;


            }
            else
            {
                string[] evirAssets = new string[2];
                evirAssets[0] = "Assets/Resources/" + go1.name + ".prefab";
                evirAssets[1] = "Assets/Resources/" + envirname + "_skybox.mat";

                buildMap[0].assetNames = evirAssets;

            }

        }
        else
        {

            //Place the lightmap data here
            LightingDataAsset templights = Lightmapping.lightingDataAsset;
            if (templights != null)
            {
                string[] evirAssets = new string[6];
                evirAssets[0] = "Assets/Resources/" + go1.name + ".prefab";
                //adding the skybox in the zone
                Material mats = new Material(RenderSettings.skybox);
                mats.name = envirname + "_skybox.mat";
                AssetDatabase.CreateAsset(mats, AssetDatabase.GenerateUniqueAssetPath("Assets/Resources/" + envirname + "_skybox.mat"));
                evirAssets[1] = "Assets/Resources/" + envirname + "_skybox.mat";

                string assetPath = AssetDatabase.GetAssetPath(templights);
                Debug.Log("light path nosky/light assetPath:" + assetPath);
                evirAssets[2] = "Assets/scopiro/scorpioofficeurpfinal/Lightmap-0_comp_dir.png";
                evirAssets[3] = "Assets/scopiro/scorpioofficeurpfinal/Lightmap-0_comp_light.exr";
                evirAssets[4] = "Assets/scopiro/scorpioofficeurpfinal/ReflectionProbe-0.exr";
                evirAssets[5] = "Assets/scopiro/scorpioofficeurpfinal/ReflectionProbe-1.exr";
                buildMap[0].assetNames = evirAssets;
                Debug.Log("light path nosky/light number of things:" + buildMap[0].assetNames.Length);
                Debug.Log("light path nosky/light last one:" + buildMap[0].assetNames[2]);


            }
            else
            {
                string[] evirAssets = new string[2];
                evirAssets[0] = "Assets/Resources/" + go1.name + ".prefab";
                //adding the skybox in the zone
                Material mats = new Material(RenderSettings.skybox);
                mats.name = envirname + "_skybox.mat";
                AssetDatabase.CreateAsset(mats, AssetDatabase.GenerateUniqueAssetPath("Assets/Resources/" + envirname + "_skybox.mat"));
                evirAssets[1] = "Assets/Resources/" + envirname + "_skybox.mat";

                buildMap[0].assetNames = evirAssets;

            }

        }
        */
        // Create folders if they dont exist
        validateOutputPaths();

        // Create asset bundle in designated folder
        BuildPipeline.BuildAssetBundles("Assets/ABs/and/", buildMap, BuildAssetBundleOptions.None, BuildTarget.Android);
        await Task.Yield();
        Debug.Log("After Android...");
    }

    // Android Uploader
    async Task uploadAssBuildAnd(string envirName, GameObject go1, string localPathUnity)
    {
        // Get path to asset
        string filepath = localPathUnity + @"\Assets\ABs\and\" + envirName;
        //Debug.Log("Starting Android Upload ");

        // Upload Asset to servers
        uvrcntrl.UVRUpload(envirName, Platforms.Android, filepath);
        await Task.Yield();
    }

    // Windows Uploader
    async Task uploadAssBuildWin(string envirName, GameObject go1, string localPathUnity)
    {
        // Get path to asset
        string filePath = localPathUnity + @"\Assets\ABs\win\" + envirName;
        //Debug.Log("Starting Window Upload ");

        // Upload Asset to servers
        uvrcntrl.UVRUpload(envirName, Platforms.Windows, filePath);
        await Task.Yield();
    }


    // Helper Functions

    // Validate and create output path if necesary
    static void validateOutputPaths()
    {
        if (!AssetDatabase.IsValidFolder("Assets/ABs"))
            AssetDatabase.CreateFolder("Assets", "ABs");

        if (!AssetDatabase.IsValidFolder("Assets/ABs/and"))
            AssetDatabase.CreateFolder("Assets/ABs", "and");

        if (!AssetDatabase.IsValidFolder("Assets/ABs/win"))
            AssetDatabase.CreateFolder("Assets/ABs", "win");
    }

    // Wipe Resource folder
    // Create if needed
    private static void clensResourceFolder()
    {
        if (AssetDatabase.IsValidFolder("Assets/Resources"))
        {
            // already made
            FileUtil.DeleteFileOrDirectory("Assets/Resources");

        }
        AssetDatabase.CreateFolder("Assets", "Resources");
    }

}

