#if UNITY_EDITOR

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.Compilation;
using UnityEngine;

public class DialogueBuildProcessor : IPreprocessBuildWithReport, IPostprocessBuildWithReport
{
    public int callbackOrder => 0;

    public void OnPreprocessBuild(BuildReport report)
    {
        Debug.Log(":: begin dialogue import");
        if (DialogueDatabase.Import() != 0) throw new BuildFailedException(":: dialogue import failed");
        Debug.Log(":: dialogue import complete");
    }
    
    public void OnPostprocessBuild(BuildReport report)
    {
        Debug.Log($"DialogueBuildProcessor.OnPostprocessBuild for target {report.summary.platform} at path {report.summary.outputPath}");
        
        // copy dialogue csv to build _Data folder
        var dir = Path.GetDirectoryName(report.summary.outputPath);
        if (dir == null) throw new BuildFailedException("no build directory");

        var dataDir = Directory
            .GetDirectories(dir)
            .Single(p => p.EndsWith("_Data"));
        var buildPath = Path.Combine(dataDir, DialogueDatabase.DIALOGUE_FILENAME);
        
        File.Copy(DialogueDatabase.EDITOR_DialogueFile, buildPath);
        Debug.Log($":: copied dialogue file {DialogueDatabase.EDITOR_DialogueFile} to output folder {buildPath}");
    }
}

#endif