using Editor.MapDoc;
using NativeHammer;
using System.IO;
using System.Text.Json.Nodes;

namespace Editor.MapEditor;

/// <summary>
/// This is our CQHammerMainWnd
/// </summary>
public partial class HammerSession
{
	CHammerEditorSession _native;

	internal HammerSession( CHammerEditorSession n )
	{
		_native = n;

		Log.Info( "New session started!" );
	}

	internal static HammerSession Create( CHammerEditorSession native, CHammerApp app )
	{
		var s = new HammerSession( native );

		InteropSystem.Alloc( s );
		return s;
	}

	/// <summary>
	/// The map that this session is editing
	/// </summary>
	public Asset MapAsset => AssetSystem.Get( _native.GetMapAsset() );

	public MapDoc.MapDocument MapDocument => _native.GetMapDoc();

	/// <summary>
	/// The absolute path to the .vpk generated by this map
	/// </summary>
	public string CompiledMapPath => Path.ChangeExtension( MapAsset.AbsolutePath, ".vpk" );

	/// <summary>
	/// Called when c++ destroys us
	/// </summary>
	internal void Destroyed()
	{
		_native = default;
		InteropSystem.Free( this );

		Log.Info( "session destroyed!" );
	}

	internal void LaunchMapInEngine()
	{
		var asset = AssetSystem.Get( _native.GetMapAsset() );
		EditorScene.PlayMap( asset );
	}

	internal void OnPreCompileFinished()
	{

	}

	internal void OnPostCompileFinished()
	{
		SceneMap.OnMapUpdated?.Invoke( "Ignore Me" );
	}

	internal bool OnPaste()
	{
		var text = EditorUtility.Clipboard.Paste();

		if ( Json.TryDeserialize<IEnumerable<JsonObject>>( text, out var serializedObjects ) )
		{
			Selection.Clear();

			foreach ( var jso in serializedObjects )
			{
				SceneUtility.MakeIdGuidsUnique( jso );

				var go = MapDocument.World.Scene.CreateObject();
				go.Deserialize( jso );
				go.MakeNameUnique();

				var mgo = new MapGameObject( MapDocument, go );
				Selection.Add( mgo );
			}

			return true;
		}

		return false;
	}
}
