﻿using AI.Core.TcpServer;
using AI.Interfaces;
using AI.Life;
using AI.Organs.Eye;
using AI.Organs.KeyboardOrgan;
using AI.Organs.Mouse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AI.Test
{
    class Program
    {
        private static bool _running = true;
        private static List<IOrgan> _organs;
        private static int _port = 36982;
        private static StateMonitoringServer _server;

        static void Main(string[] args)
        {
            _organs = new List<IOrgan>
            {
                new LifeOrgan(),
                new EyeOrgan(),
                new KeyboardOrgan(),
                new MouseOrgan()
            };

            Console.WriteLine("Preparing organs");
            foreach (var organ in _organs)
            {
                if (organ is LifeOrgan || organ is KeyboardOrgan)
                    organ.DataChanged += Organ_DataChanged;

                Console.WriteLine(organ);
                organ.Prepare().Wait();
            }

            //Console.WriteLine("Waiting for organ first initialization");
            //Task.Delay(20000).Wait();
            Console.WriteLine();
            Console.WriteLine($"Starting server on port {_port}");
            _server = new StateMonitoringServer(_port);
            _server.SetSources(_organs);
            _server.Start();
            Console.WriteLine("Server started");

            var wait = new SpinWait();
            while (_running)
            {
                wait.SpinOnce();
            }
            Console.WriteLine("Press enter to quit...");
            Console.ReadLine();
        }

        private static void Organ_DataChanged(object sender, byte[] data)
        {
            if (sender is LifeOrgan && data[0] == 0)
            {
                Console.WriteLine("I am dying.");
                _running = false;
                foreach (var o in _organs)
                {
                    Console.WriteLine($"Stopping {o.GetType().FullName}");
                    o.Stop();
                }
                Console.WriteLine("RIP me...");
            }

            if (sender is KeyboardOrgan)
            {
                var organ = sender as KeyboardOrgan;
                if (KeyboardOrgan.IsKeyActive(organ, Keys.Escape, data) && KeyboardOrgan.IsKeyActive(organ, Keys.End, data))
                {
                    Console.WriteLine("Killing switch activated. Force Stopping life...");
                    var lifeOrgan = _organs.FirstOrDefault(o => o is LifeOrgan);
                    if (lifeOrgan != null)
                        lifeOrgan.Push(new byte[1] { 0 });
                }
            }
        }
    }
}
