using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TELTest {
    public class BaseQuizContext {
        public BaseQuizContext(ConnectionHandler handler, NetworkStream stream, QuizContainer quiz) {
            Handler = handler;
            Stream = stream;
            Quiz = quiz;
        }
        public ConnectionHandler Handler { get; }
        public NetworkStream Stream { get; }
        public QuizContainer Quiz { get; }
        public async Task Handle() {
            int selection = 0;
            var selected = QuizGamemode.Registry[selection];
            while (true) {
                selected = QuizGamemode.Registry[selection < QuizGamemode.Registry.Count? selection : 0];
                await Handler.TryClear(Stream);
                await Handler.WriteASCII(Stream, Localization.UI["SELECTGAME"] + "\r\n");
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < QuizGamemode.Registry.Count + 1; i++) {
                    var item = (QuizGamemode.Registry.Count < 1 || i >= QuizGamemode.Registry.Count) ? null : QuizGamemode.Registry[i < QuizGamemode.Registry.Count? i : 0];
                    if (i == selection)
                        sb.Append(" -> ");
                    else
                        sb.Append("    ");
                    sb.AppendLineRN(item == null? "Powrot..." : item.Name);
                }
                sb.AppendLineRN("\r\n");
                sb.AppendLineRN(selection == QuizGamemode.Registry.Count? "Powrot do menu." : (selected.Name + ": " +  selected.Description));
                sb.Append("\r\n[W/S/ENTER] ");
                await Handler.WriteASCII(Stream, sb.ToString());
                char c = char.ToUpper(await Handler.ReadChar(Stream, false));
                if (c == '\n' || c == '\r') {
                    Handler.Flush(Stream);
                    break;
                }
                if (c == 'W') {
                    if (selection == 0) {
                        selection = QuizGamemode.Registry.Count;
                    } else {
                        selection--;
                    }
                }
                if (c == 'S') {
                    if (selection == QuizGamemode.Registry.Count) {
                        selection = 0;
                    } else {
                        selection++;
                    }
                }
            } // ENDOF While
            if (selection == QuizGamemode.Registry.Count) return;
            var sel = selected.CreateCheckInstance(Quiz, this);
            //Console.WriteLine(Quiz.SerializeXML());
            await Handler.TryClear(Stream);
            await sel.Begin();
        }
    }
}
