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

using FilterAPI;
using FilterAPI.Systems;
using FilterAPI.Networking;

namespace FilterTimers.Timers
{
    internal class DayNightTimer
    {
        #region Timer Variables

        private Int32 Interval;
        private Boolean Reset;
        private Byte R = 255;
        private Byte G = 255;
        private Byte B = 255;

        #endregion

        private Boolean IsDone = true;

        public DayNightTimer(Int32 I)
        {
            Interval = I;

            Thread NewThread = new Thread(delegate ()
            {
                while (true)
                {
                    Thread.Sleep(Interval * 1000);

                    if (IsDone) { Run(); }
                }
            });

            NewThread.Start();
        }

        private void Run()
        {
            IsDone = false;

            try
            {
                using (var LocalPacket = new Packet(5, 17))
                {
                    LocalPacket.PacketWriter.Write(R);
                    LocalPacket.PacketWriter.Write(G);
                    LocalPacket.PacketWriter.Write(B);

                    Program.LocalClient.SendPacket(LocalPacket);
                }

                if (Reset)
                {
                    R += 1;
                    G += 1;
                    B += 1;
                }
                else
                {
                    R -= 1;
                    G -= 1;
                    B -= 1;
                }

                if (R == 155 || G == 155 || B == 155) { Reset = true; }
                else if (R == 255 || G == 255 || B == 255) { Reset = false; }
            }
            catch (Exception Error) { Program.SendConsoleText(ConsoleColor.Red, "Timers error - Day night timer\n{0}", Error.ToString()); }

            IsDone = true;
        }
    }
}
