using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

namespace NeonTea.Quakeball.Interface {
    public class TerminalStdio : UnityEngine.MonoBehaviour {
        public int SleepBeforeInputMillis;
        public Terminal Terminal;
#if UNITY_SERVER
        private Thread StdioThread;
        private int MessageIndex = 0;
        private ConcurrentQueue<string> Commands = new ConcurrentQueue<string>();

        private void Awake() {
            StdioThread = new Thread(new ThreadStart(StdioMain));
            StdioThread.IsBackground = true;
            StdioThread.Start();
        }

        private void Update() {
            string cmd;
            while (Commands.TryDequeue(out cmd)) {
                Terminal.Run(cmd);
            }
            List<string> prints = Terminal.GetMessagesSince(ref MessageIndex);
            if (prints.Count > 0) {
                foreach (string print in prints) {
                    Console.Out.Write($"{print}\n");
                }
                Console.Out.Write("[Quakeball]: ");
                Console.Out.Flush();
            }
        }

        private void StdioMain() {
            Console.Out.WriteLine($"Console thread started, waiting a {SleepBeforeInputMillis} ms for everything to start up.");
            Thread.Sleep(SleepBeforeInputMillis);
            Console.Out.WriteLine("#########################");
            Console.Out.WriteLine("# Welcome to Quakeball! #");
            Console.Out.WriteLine("#########################");
            Console.Out.WriteLine(" (Try writing \"help\"!)");
            Console.Out.Write("\n[Quakeball]: ");
            while (true) {
                string cmd = Console.In.ReadLine().Trim();
                if (cmd != null && cmd.Length > 0) {
                    Commands.Enqueue(cmd);
                }
            }
        }
#endif
    }
}
