Editor/GolfKitMenu.cs
using Sandbox;
using Editor;
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// The Golf Kit menu in the editor's menu bar, for the open scene: Add hole (the next hole group
/// with a cup, a tee, a flag and a floor tile, 16000 units past the last hole), Check course (what
/// is missing or wrong, per hole, in the console and a dialog), and the bounds ring for the
/// selected hole. Publish course.. is in <see cref="GolfCourseProjectMeta"/>. Every entry is one
/// undo step. The hole colliders are also rebuilt after every scene save.
/// </summary>
public static class GolfKitMenu
{
	public const string CupPrefab = "prefabs/cup.prefab";
	public const string TeePrefab = "prefabs/tee.prefab";
	public const string FlagPrefab = "prefabs/flag.prefab";
	public const string FloorPrefab = "prefabs/holekit/floor_tile.prefab";

	/// <summary>How far apart Add hole places the holes, along X.</summary>
	public const float HoleSpacing = 16000f;

	// ---------------------------------------------------------------- Add hole

	[Menu( "Editor", "Golf Kit/Add hole", "add_location" )]
	public static void AddHole()
	{
		var session = SceneEditorSession.Active;
		var scene = session?.Scene;
		if ( scene is null ) { Log.Warning( "Golf Kit: Add hole needs an open scene" ); return; }

		using var sceneScope = scene.Push();
		var holes = HoleGroups( scene );
		var number = holes.Count + 1;
		var last = holes.LastOrDefault();
		var origin = last.IsValid() ? last.WorldPosition + new Vector3( HoleSpacing, 0f, 0f ) : Vector3.Zero;

		using var undo = session.UndoScope( "Add hole" ).WithGameObjectCreations().WithComponentCreations().Push();

		var group = new GameObject( true, $"Hole {number}" );
		group.WorldPosition = origin;
		var hole = group.Components.Create<Hole>();
		hole.Title = $"Hole {number}";
		hole.Par = 3;

		// One floor tile with the tee on it, the cup tile beyond it, the flag beside the cup.
		var floor = Place( FloorPrefab, group, new Vector3( 0f, 0f, 0f ), "Floor" );
		var cup = Place( CupPrefab, group, new Vector3( 200f, 0f, 0f ), "Cup" );
		var tee = Place( TeePrefab, group, new Vector3( -50f, 0f, 0f ), "Tee" );
		var flag = Place( FlagPrefab, group, new Vector3( 220f, 20f, 0f ), "Flag" );

		var missing = new[] { (floor, FloorPrefab), (cup, CupPrefab), (tee, TeePrefab), (flag, FlagPrefab) }.Where( p => !p.Item1.IsValid() ).Select( p => p.Item2 ).ToList();
		if ( missing.Count > 0 ) Log.Warning( $"Golf Kit: Add hole could not load {string.Join( ", ", missing )}" );

		hole.Components.GetOrCreate<GolfHoleCollision>().MarkDirty();
		Log.Info( $"Golf Kit: Hole {number} added at {origin:0} with a floor tile, cup, tee and flag; drag more tiles in and draw the rails with the Course Wall Builder" );
	}

	/// <summary>A prefab under the group at a position local to it. Clone takes its transform as local to the parent already.</summary>
	static GameObject Place( string prefab, GameObject parent, Vector3 local, string name )
	{
		var go = GameObject.Clone( prefab, new Transform( local, Rotation.Identity ), parent, true, name );
		if ( go.IsValid() ) go.LocalPosition = local;
		return go;
	}

	/// <summary>The hole groups of a scene (objects with a Golf Hole, not the old layout) in hierarchy order.</summary>
	public static List<GameObject> HoleGroups( Scene scene )
	{
		var result = new List<GameObject>();
		void Walk( GameObject go )
		{
			foreach ( var child in go.Children.ToList() )
			{
				if ( !child.IsValid() ) continue;
				var hole = child.GetComponent<Hole>( true );
				if ( hole is not null && !hole.IsOldLayout ) result.Add( child );
				Walk( child );
			}
		}
		Walk( scene );
		return result;
	}

	// ---------------------------------------------------------------- Check course

	[Menu( "Editor", "Golf Kit/Check course", "fact_check" )]
	public static void CheckCourse()
	{
		var session = SceneEditorSession.Active;
		var scene = session?.Scene;
		if ( scene is null ) { Log.Warning( "Golf Kit: Check course needs an open scene" ); return; }
		using var sceneScope = scene.Push();

		var lines = new List<string>();
		var moved = 0;
		var oldLayout = scene.GetAllComponents<Hole>().Any( h => h.IsValid() && h.IsOldLayout );
		if ( oldLayout )
		{
			using var undo = session.UndoScope( "Bring holes to the current layout" ).WithComponentCreations().WithComponentChanges( scene.GetAllComponents<Hole>().Where( h => h.IsOldLayout ) ).Push();
			moved = Hole.MigrateOldLayout( scene );
			if ( moved > 0 ) lines.Add( $"{moved} hole(s) were in the old layout (Golf Hole on the cup) and have been moved to their group; save the scene." );
		}

		var groups = HoleGroups( scene );
		if ( groups.Count == 0 )
			lines.Add( "No hole: no object with a Golf Hole component. Use Golf Kit > Add hole." );

		var number = 0;
		foreach ( var group in groups )
		{
			number++;
			var hole = group.GetComponent<Hole>( true );
			var problems = new List<string>();
			if ( !group.Enabled ) problems.Add( "the group is disabled, so the game skips it" );
			if ( !hole.Enabled ) problems.Add( "its Golf Hole component is disabled" );
			if ( string.IsNullOrWhiteSpace( hole.Title ) ) problems.Add( "no title (the HUD shows nothing)" );
			var cup = group.GetComponentInChildren<GolfCup>( true );
			if ( cup is null ) problems.Add( "no cup: drag prefabs/cup.prefab (or a cup variant) into the group" );
			else if ( !cup.Active ) problems.Add( $"the cup \"{cup.GameObject.Name}\" is disabled" );
			else if ( cup.GetComponent<ModelRenderer>( true )?.Model is null ) problems.Add( $"the cup \"{cup.GameObject.Name}\" has no model" );
			var tee = group.GetComponentInChildren<GolfTee>( true );
			if ( tee is null ) problems.Add( "no tee: drag prefabs/tee.prefab into the group (balls would start at the cup)" );
			else if ( !tee.Active ) problems.Add( $"the tee \"{tee.GameObject.Name}\" is disabled" );
			var floors = group.GetComponentsInChildren<ModelRenderer>( true ).Count( r => r.IsValid() && r.Model is not null && r.GameObject.GetComponent<GolfCup>( true ) is null && r.GameObject.GetComponentInParent<GolfTee>( true ) is null );
			if ( floors == 0 ) problems.Add( "no floor pieces: drag tiles from prefabs/holekit or prefabs/trench into the group" );
			var collision = group.GetComponent<GolfHoleCollision>( true );
			if ( collision is null ) problems.Add( "no Golf Hole Collision (the Golf Hole adds it when the scene is reopened)" );
			else if ( collision.Triangles == 0 ) problems.Add( "the hole's collision has no triangles yet (pieces with a Model Collider are merged on the next update)" );
			if ( cup is not null && tee is not null && cup.WorldPosition.Distance( tee.WorldPosition ) < 50f ) problems.Add( "the tee is on top of the cup" );

			var head = $"Hole {number} (\"{group.Name}\", title \"{hole.Title}\", par {hole.Par}): ";
			lines.Add( head + (problems.Count == 0 ? "ok" : string.Join( "; ", problems )) );
		}

		var extras = scene.GetAllComponents<CameraComponent>().Where( c => c.IsValid() && c.GameObject.GetComponent<GolfMenuCamera>( true ) is null && c.GameObject.GetComponent<GolfPreviewCamera>( true ) is null ).ToList();
		if ( extras.Count > 0 ) lines.Add( $"{extras.Count} extra camera(s) ({string.Join( ", ", extras.Select( c => c.GameObject.Name ) )}): the game removes them; Set up course does too." );
		if ( !scene.GetAllComponents<GolfCourseInfo>().Any() ) lines.Add( "No Golf Course Info: the course has no name, ambience or wall style. Set up course adds one." );
		if ( !scene.GetAllComponents<GolfMenuCamera>().Any() ) lines.Add( "No Golf Menu Camera: the game's menu orbits the first hole instead. Set up course adds one." );
		if ( !scene.GetAllComponents<SpawnPoint>().Any() ) lines.Add( "No Spawn Point: players stand at the origin until the first hole starts (optional)." );

		var okCount = groups.Count - lines.Count( l => l.StartsWith( "Hole " ) && !l.EndsWith( ": ok" ) );
		var summary = groups.Count == 0 ? "Nothing to play yet." : $"{groups.Count} hole(s), {okCount} ok.";
		var report = summary + "\n\n" + string.Join( "\n", lines.Count == 0 ? new[] { "Nothing missing." } : lines );
		Log.Info( "Golf Kit: Check course\n" + report );
		try { Dialog.AskConfirm( () => { }, report, "Golf Kit: Check course", "OK", "Close" ); }
		catch ( Exception e ) { Log.Info( $"Golf Kit: the Check course dialog could not be shown ({e.Message}); the list is in the console" ); }
	}

	// ---------------------------------------------------------------- bounds ring

	[Menu( "Editor", "Golf Kit/Add bounds to selected hole", "fence" )]
	public static void AddBounds()
	{
		var collision = SelectedHoleCollision( out var why );
		if ( collision is null ) { Log.Warning( $"Golf Kit: Add bounds: {why}" ); return; }
		GolfHoleEdgeWalls.Add( collision );
	}

	[Menu( "Editor", "Golf Kit/Remove bounds from selected hole", "delete" )]
	public static void RemoveBounds()
	{
		var collision = SelectedHoleCollision( out var why );
		if ( collision is null ) { Log.Warning( $"Golf Kit: Remove bounds: {why}" ); return; }
		GolfHoleEdgeWalls.Remove( collision );
	}

	/// <summary>The Golf Hole Collision of the selected object's hole group (the object or its nearest ancestor with a Golf Hole).</summary>
	static GolfHoleCollision SelectedHoleCollision( out string why )
	{
		why = null;
		var session = SceneEditorSession.Active;
		var selected = EditorScene.Selection.OfType<GameObject>().FirstOrDefault();
		if ( !selected.IsValid() ) { why = "select the hole's group (or anything inside it) first"; return null; }
		using var sceneScope = session.Scene.Push();
		var hole = selected.GetComponentInParent<Hole>( true, true );
		if ( hole is null ) { why = $"\"{selected.Name}\" is not inside a hole group (an object with a Golf Hole)"; return null; }
		return hole.Components.GetOrCreate<GolfHoleCollision>();
	}

	// ---------------------------------------------------------------- on save

	/// <summary>After every scene save, every hole's collider is rebuilt from its pieces (the collider itself is never saved; this keeps the editor's copy current).</summary>
	[Event( "scene.saved" )]
	static void OnSceneSaved( Scene scene )
	{
		if ( scene is null ) return;
		var count = 0;
		foreach ( var collision in scene.GetAllComponents<GolfHoleCollision>() )
		{
			if ( !collision.IsValid() ) continue;
			collision.MarkDirty();
			count++;
		}
		if ( count > 0 ) Log.Info( $"Golf Kit: {count} hole collider(s) rebuilt after the save of {scene.Source?.ResourcePath ?? scene.Name}" );
	}
}