using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

namespace CommandExtensions.Commands {
	[UsedImplicitly]
	public class TestLogSpam : ConsoleCmdAbstract {
		public override string[] getCommands () {
			return new[] { "tls" };
		}

		public override bool AllowedInMainMenu => true;

		public override bool IsExecuteOnClient => true;

		public override string getDescription () {
			return "Spams the log with until stopped";
		}

		public override string getHelp () {
			return @"
			|Usage:
			|  1. tls <N> ['second']
			|  2. tls stop
			|1. Start spamming with N messages per frame - or per second if the second argument is the word 'second'
			|2. Stop spamming
			".Unindent ();
		}

		private Coroutine spamCoroutine;
		private WaitForSeconds waitObj;

		public override void Execute (List<string> _params, CommandSenderInfo _senderInfo) {
			if (_params.Count != 1 && _params.Count != 2) {
				SdtdConsole.Instance.Output ($"Wrong number of arguments, expected 1 or 2, found {_params.Count}.");
				return;
			}

			if (_params [0].EqualsCaseInsensitive ("stop")) {
				if (spamCoroutine == null) {
					SdtdConsole.Instance.Output ("Not spamming.");
					return;
				}

				ThreadManager.StopCoroutine (spamCoroutine);
				spamCoroutine = null;
				SdtdConsole.Instance.Output ("Spam stopped.");
				return;
			}

			if (!int.TryParse (_params [0], out int count)) {
				SdtdConsole.Instance.Output ("The given spam number is not a valid integer");
				return;
			}

			bool perSecond = _params.Count > 1 && _params [1] == "second";

			waitObj = perSecond ? new WaitForSeconds (1f) : null;

			SdtdConsole.Instance.Output ($"Started spamming {count} messages per {(perSecond ? "second" : "frame")}");
			spamCoroutine = ThreadManager.StartCoroutine (SpamCo (count));
		}

		private IEnumerator SpamCo (int _count) {
			do {
				for (int i = 0; i < _count; i++) {
					Log.Out ("This is a spam log message.");
				}

				yield return waitObj;
			} while (spamCoroutine != null);
		}
	}
}