// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
#if VRC_SDK_VRCSDK3
using UnityEditor;
using VRC.SDKBase.Editor.BuildPipeline;

namespace WPFMA.Team
{
    /// <summary>
    /// Runs when the VRChat SDK starts a build or upload during a Team session. Tells the teammate, warns if they
    /// are uploading right now, and reminds the guest that the avatar or world ID belongs to whoever uploaded it.
    /// </summary>
    internal sealed class TeamUploadGuard : IVRCSDKBuildRequestedCallback
    {
        private const string GuestWarnedKey = "WPFMA.Team.GuestUploadWarned";

        public int callbackOrder
        {
            get { return -100; }
        }

        public bool OnBuildRequested(VRCSDKRequestedBuildType requestedBuildType)
        {
            if (!TeamSession.IsLinked)
                return true;

            string name = TeamSession.RemoteName ?? "Your teammate";
            string kind = requestedBuildType == VRCSDKRequestedBuildType.Avatar ? "avatar" : "world";

            // Everyone's latest changes have to be here first, or the upload leaves some of them out.
            var notReady = TeamSession.NotReady();
            if (notReady.Count > 0 &&
                !EditorUtility.DisplayDialog("Team: not everyone is synced yet",
                    "Some changes are still on their way:\n\n• " + string.Join("\n• ", notReady.ToArray()) +
                    "\n\nUploading now can leave those changes out of the " + kind + ". Wait until the Team tab says " +
                    "\"Ready to upload\", then try again.", "Upload anyway", "Wait"))
                return false;

            if (TeamSession.Now - TeamSession.RemoteUploadAt < 180 &&
                !EditorUtility.DisplayDialog("Team", name + " started building or uploading a few moments ago. Uploading at the same " +
                                                     "time can replace their upload.", "Continue anyway", "Cancel"))
                return false;

            if (!TeamSession.IsHost && !SessionState.GetBool(GuestWarnedKey, false))
            {
                if (!EditorUtility.DisplayDialog("Team",
                        "This " + kind + "'s ID belongs to the account that first uploaded it - usually " + name + ". Uploading from your " +
                        "account will fail if you don't own it.\n\nAsk " + name + " to upload, or continue for a local test build.",
                        "Continue", "Cancel"))
                    return false;
                SessionState.SetBool(GuestWarnedKey, true);
            }

            TeamSession.Send(new TeamMessage { t = "upl", m = kind });
            return true;
        }
    }
}
#endif
#endif
