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

        [MenuItem("TWSDK/Export Scene")]
        public static void ExportScene()
        {
            var scene = SceneManager.GetActiveScene();
            string fullpath = EditorUtility.SaveFilePanel("Export scene", ".", scene.name, "trscene");
            if (fullpath == null)
                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 };

                BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { bundleBuild }, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
                if (File.Exists(fullpath))
                    File.Delete(fullpath);
                File.Move(Application.temporaryCachePath + "/" + filename, fullpath);

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