﻿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;

public class utopiavrkituploader : EditorWindow
{
    public uvrloader uvrcntrl = new uvrloader();
    //public uvrloader uvrcntrl;

    bool isandroid = true;
    bool iswindow = true;
    //bool iswindow = false;
    string envirname = "name";
    string itemkitname = "name";
    string username = "name";
    string password = "password";
    int lastnameselected = 0;
    int _selected = 0;
    bool firsttime = true;
    bool worldsetup = false;
    bool worldlock = false;

    // scroll bar
    private int screenBoxX = Screen.width;
    private int screenBoxY = Screen.height;

    private int scrollBoxX = Screen.width - 10;
    private int scrollBoxY = Screen.height * 3;

    public Vector2 scrollPosition = Vector2.zero;
    private string[] itemlist;
    string status = "";


    [MenuItem("UtopiaVR/Utopiavrkitcreator")]
    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<utopiavrkituploader>("UtopiaVR Item Kit uploader").position = new Rect(0, 0, 700, 600);
    }


    async void prefabtask( GameObject go1)
    {
        await customtexturebuild(go1);
        await customprefadbuild(go1);
    }
    async static Task customtexturebuild(GameObject go1)
    {
        //save and make textures for uploading to the site
        Texture2D image = UnityEditor.AssetPreview.GetAssetPreview(go1);
        byte[] bytes = image.EncodeToPNG();

        // For testing purposes, also write to a file in the project folder
        if (AssetDatabase.IsValidFolder("Assets/SavesAssets/itemtextures"))
        {
            // already made
            //FileUtil.DeleteFileOrDirectory("Assets/Resources");
            //AssetDatabase.CreateFolder("Assets", "Resources");
        }
        else
        {
            AssetDatabase.CreateFolder("Assets", "SavesAssets");
            AssetDatabase.CreateFolder("Assets/SavesAssets", "itemtextures");
        }
        //File.WriteAllBytes(Application.dataPath + "/SavesAssets/itemtextures/" + go1.name + ".png", bytes);
        await writefilebuild(go1, bytes);
        await Task.Yield();
        AssetDatabase.Refresh();
        Debug.Log("texure made for..." + go1.name);

    }

    async static Task writefilebuild(GameObject go1, byte[] bytes)
    {
        File.WriteAllBytes(Application.dataPath + "/SavesAssets/itemtextures/" + go1.name + ".png", bytes);
        await Task.Yield();


    }


    async static Task customprefadbuild( GameObject go1)
    {
        string localkpath = "Assets/Resources2/" + go1.name + ".prefab";
        if (AssetDatabase.IsValidFolder("Assets/Resources2"))
        {
            // already made
            //FileUtil.DeleteFileOrDirectory("Assets/Resources");
            //AssetDatabase.CreateFolder("Assets", "Resources");
        }
        else
        {
            AssetDatabase.CreateFolder("Assets", "Resources2");
        }

        localkpath = AssetDatabase.GenerateUniqueAssetPath(localkpath);
        PrefabUtility.SaveAsPrefabAsset(go1, localkpath);
        await Task.Yield();
        Debug.Log("prefab made for..." + go1.name);

    }
    async static Task windowassbuild(string envirname, string[] go1)
    {
        Debug.Log("Starting Window build ");
        AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
        buildMap[0].assetBundleName = envirname;
        string[] evirAssets = new string[go1.Length];
        int i = 0;
        foreach(string tempname in go1)
        {
            evirAssets[i] = "Assets/Resources2/" + go1[i] + ".prefab";
            i = i + 1;

        }
        buildMap[0].assetNames = evirAssets;
        if (AssetDatabase.IsValidFolder("Assets/ABs/win"))
        {
            // already made
        }
        else
        {
            if (!AssetDatabase.IsValidFolder("Assets/ABs"))
                AssetDatabase.CreateFolder("Assets", "ABs");
            AssetDatabase.CreateFolder("Assets/ABs", "win");

        }
        BuildPipeline.BuildAssetBundles("Assets/ABs/win/", buildMap, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
        await Task.Yield();
        Debug.Log("After Window build ");
    }
    async static Task androidassbuild(string envirname, string[] go1)
    {
        Debug.Log("creating Android build ");
        AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
        buildMap[0].assetBundleName = envirname;
        string[] evirAssets = new string[go1.Length];
        int i = 0;
        foreach (string tempname in go1)
        {
            evirAssets[i] = "Assets/Resources2/" + go1[i] + ".prefab";
            i = i + 1;

        }
        buildMap[0].assetNames = evirAssets;
        if (AssetDatabase.IsValidFolder("Assets/ABs/and"))
        {
            // already made
        }
        else
        {
            if (!AssetDatabase.IsValidFolder("Assets/ABs"))
                AssetDatabase.CreateFolder("Assets", "ABs");
            AssetDatabase.CreateFolder("Assets/ABs", "and");
        }

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

    async void buildtask()
    {
        //build assets bunddle
        //build asset window
        uvrcntrl.statusprogress = "Please wait building assets";
        if (iswindow)
        {
            await windowassbuild(itemkitname, itemlist);

        }
        //build asset android
        if (isandroid)
        {
            await androidassbuild(itemkitname, itemlist);

        }

        //upload the bunddle


        string localpathunity = System.IO.Directory.GetCurrentDirectory();
        string filepath = localpathunity + @"\Assets\SavesAssets\itemtextures\";
        //upload the images
        string filename_bundle = itemkitname;
        string filepath_bundle = localpathunity + @"\Assets\ABs\";
        string initialPath_bundle = "2";//1 windows 2 android 3 both
        if (isandroid && iswindow)
        {
            initialPath_bundle = "3";//1 windows 2 android 3 both
        }
        else
        {
            if (isandroid)
            {
                initialPath_bundle = "2";//1 windows 2 android 3 both
            }
            //upload asset window
            if (iswindow)
            {
                initialPath_bundle = "1";//1 windows 2 android 3 both
            }

        }

        uvrcntrl.UVRtexturebuildkupload(itemlist, filepath, itemkitname,filename_bundle, filepath_bundle, initialPath_bundle);
        //status = "textures are uploaded please wait connecting to account";
        //add the items to the database
        //itemkitname = kitname to get the id
        //go.name to get the name of item and the name of the image
        //the image name will be the /playerid/itempic/
        //itemkitname, itemlist
            //uvrcntrl.UVRitemlistbuildkdb(itemlist, itemkitname);
        //await uvrcntrl.UVRtexturebuildkupload(itemlist);

        //await customtexturebuild(go1);
        //await customprefadbuild(go1);
        await Task.Yield();
    }




    private void OnGUI()
    {
        //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, 200, 100), tex);
        GUILayout.Label("", EditorStyles.boldLabel);
        GUILayout.Label("", EditorStyles.boldLabel);
        GUILayout.Label("", EditorStyles.boldLabel);
        GUILayout.Label("", EditorStyles.boldLabel);
        GUILayout.Label("", EditorStyles.boldLabel);
        GUILayout.Label("", EditorStyles.boldLabel);
        GUILayout.Label("Upload items kits to UtopiaVR", EditorStyles.boldLabel);
        if (uvrcntrl.loggedin == false)
        {
            username = EditorGUILayout.TextField("username Name: ", username.ToUpper());
            password = EditorGUILayout.TextField("password Name: ", password);
            if (GUILayout.Button("log in"))
            {
                uvrcntrl.UVRlogin(username, password);

            }
        }
        else
        {



            //time to make some items
            if (GUI.Button(new Rect(10, 120, 100, 25), "Refresh kit list"))
            {
                //list the kits that this person has control of.
                uvrcntrl.UVRitemkitslist(uvrcntrl.accountid);
            }
            if (GUI.Button(new Rect(115, 120, 100, 25), "Create new kit"))
            {

            }
            if (GUI.Button(new Rect(220, 120, 215, 25), "Convert gameobjects to kit prefabs"))
            {
                //get the selected objects
                UnityEngine.Object[] objects = Selection.objects;

                //create resources if needed
                if (AssetDatabase.IsValidFolder("Assets/Resources"))
                {
                    // already made
                    //FileUtil.DeleteFileOrDirectory("Assets/Resources");
                    //AssetDatabase.CreateFolder("Assets", "Resources");
                }
                else
                {
                    AssetDatabase.CreateFolder("Assets", "Resources");
                }
                //create texutre folder if needed
                if (AssetDatabase.IsValidFolder("Assets/itemtextures"))
                {
                    // already made
                    //FileUtil.DeleteFileOrDirectory("Assets/Resources");
                    //AssetDatabase.CreateFolder("Assets", "Resources");
                }
                else
                {
                    AssetDatabase.CreateFolder("Assets", "itemtextures");
                }
                int listnumber = 0;
                itemlist = new String[objects.Length];
                foreach (UnityEngine.Object temp in objects)
                {
                    //create the prefab of the item
                    prefabtask((GameObject)temp);
                    itemlist[listnumber] = temp.name;
                    listnumber = listnumber + 1;


                    //we need to show the list of items in  list box give a - sign to delete them if wanted

                }




            }





            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            if(uvrcntrl.itemkitname != null)
            {
                _selected = EditorGUILayout.Popup("My Simple Dropdown", _selected, uvrcntrl.itemkitname);

                if (firsttime)
                {
                    itemkitname = uvrcntrl.itemkitname[_selected];
                    Debug.Log("Currently the " + itemkitname + " Item kit is set to add this scene too");
                    firsttime = false;
                }
                if (lastnameselected != _selected)
                {
                    itemkitname = uvrcntrl.itemkitname[_selected];
                    Debug.Log("Currently the " + itemkitname + " Itemkit is set to add this scene too");
                    lastnameselected = _selected;
                }

            }


            //list of items
            GUILayout.Label("List of items in the kit", EditorStyles.boldLabel);
            scrollPosition = GUI.BeginScrollView(new Rect(10, 200, Screen.width - 200, 150), scrollPosition, new Rect(0, 0, 220, 2000));

            int row = 0;
            if (itemlist != null)
            {
                foreach (string tempname in itemlist)
                {
                    // by the last parameter to BeginScrollView.
                    GUI.Label(new Rect(0, row, 400, 20), tempname);
                    GUI.Button(new Rect(410, row, 20, 20), "-");
                    row = row + 20;

                }

            }
            // GUI.Label(new Rect(0, row, 400, 20), "object nane2");
            // GUI.Button(new Rect(410, row, 20, 20), "-");




            // End the scroll view that we began above.
            GUI.EndScrollView();


            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);
            GUILayout.Label("", EditorStyles.boldLabel);


            //envirname = EditorGUILayout.TextField("Environment Name: ", envirname);
            isandroid = GUILayout.Toggle(isandroid, " Android");
            iswindow = GUILayout.Toggle(iswindow, " Windows");

            if (itemkitname != "name")
            {
                if (GUILayout.Button("Build and Upload"))
                {

                    status = "Please Wait uploading texutures";
                    buildtask();

                }

            }
            status = uvrcntrl.statusprogress;
            GUILayout.Label(status, EditorStyles.boldLabel);

        }
    }
}
