//version: 2 (IPostprocessBuildWithReport is replaced)
using System.IO;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace BansheeGz.BGDatabase.Editor
{
    /// <summary>
    /// If database settings file is included into build by default, clear the settings file content
    /// </summary>
    public class BGDatabaseFilterOutSettingsOnPreBuild : IPreprocessBuildWithReport
    {
        private const string TempFileName = "bgdatabase_temp_settings_Qutyq.json";
        public static bool Cleared;
        public static string TempFilePath => Path.Combine(Application.temporaryCachePath, TempFileName);

        public int callbackOrder => 0;
        public void OnPreprocessBuild(BuildReport report)
        {
            if (!BGRepo.DefaultRepoLoaded) BGRepo.Load();
            if (!BGRepo.Ok) return;
            if (!BGSettingsEditor.OkWithLoad) return;

            if (!BGSettingsEditor.DefaultPathIsUsed) return;
            var path = BGEditorUtility.GetRelativePath(BGSettingsEditor.Path);
            if (string.IsNullOrEmpty(path) || !File.Exists(path)) return;
            var tempFile = TempFilePath;
            File.WriteAllText(tempFile, File.ReadAllText(path));
            Cleared = true;
            File.WriteAllText(path, "");
            AssetDatabase.ImportAsset(path);
            EditorApplication.update += WaitForBuildCompletion;
        }
        
        private void WaitForBuildCompletion()
        {
            if (BuildPipeline.isBuildingPlayer) return;
            EditorApplication.update -= WaitForBuildCompletion;

            if (!BGRepo.Ok) return;
            if (!BGSettingsEditor.Ok) return;
            if (!BGSettingsEditor.DefaultPathIsUsed) return;
            if (!Cleared) return;
            Cleared = false;
            var path = BGEditorUtility.GetRelativePath(BGSettingsEditor.Path);
            if (string.IsNullOrEmpty(path) || !File.Exists(path)) return;
            var tempFile = TempFilePath;
            if (!File.Exists(tempFile)) return;
            File.WriteAllText(path, File.ReadAllText(tempFile));
            AssetDatabase.ImportAsset(path);
            File.Delete(tempFile);
        }
    }
}