﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
using System.IO;

namespace TWSDK
{
    public class SceneExport : MonoBehaviour
    {
        public static string UNITY_VERSION = "2020.3.0f1";

        [MenuItem("TWSDK/Export Scene")]
        public static void ExportScene()
        {
            if (Application.unityVersion != UNITY_VERSION)
            {
                EditorUtility.DisplayDialog("Warning", "Unity version " + Application.unityVersion + " does not match recommended version " + UNITY_VERSION + ". The scene might not be able to be imported.", "OK");
            }

            var scene = SceneManager.GetActiveScene();
            string fullpath = EditorUtility.SaveFilePanel("Export scene", ".", scene.name, "trscene");
            if (fullpath == null || fullpath.Length == 0)
                return;

            bool complete = false;
            try
            {
                EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());

                string filename = Path.GetFileName(fullpath);

                AssetBundleBuild bundleBuild = new AssetBundleBuild();

                AssetDatabase.RemoveUnusedAssetBundleNames();
                bundleBuild.assetBundleName = filename;
                bundleBuild.assetNames = new string[] { scene.path };
                bundleBuild.addressableNames = new string[] { scene.name };

                string filewithpath = Application.temporaryCachePath + "/" + filename;

                try
                {
                    File.Delete(filewithpath);
                    File.Delete(filewithpath + ".manifest");
                }
                catch (DirectoryNotFoundException) { }

                var manifest = BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { bundleBuild }, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);

                if (File.Exists(fullpath))
                    File.Delete(fullpath);
                File.Move(filewithpath, fullpath);

                EditorUtility.DisplayDialog("Export", "Export complete!", "OK");
                complete = true;
            }
            finally
            {
                if (!complete)
                    EditorUtility.DisplayDialog("Export", "Export failed! See the console for details.", "OK");
            }
        }
    }
}