using DataservPlugin;
using System;
using System.Globalization;
using System.Linq;
using System.Net;

[PluginData(Author = "TimD", Description = "Shift Plugin", Name = "Shift Counter Reset")]
public class ShiftResetPlugin : AbstractPlugin {
    private int _lastShift = -1;
    private WebClient _webClient;
    private readonly string[] _resetUrls = { "http://localhost:19336/ResetPassFailCounter_Write", "http://localhost:19336/ResetPassFailCounter_Write2" };

    public ShiftResetPlugin()
    {
        _webClient = new WebClient();
    }

    public override int LoopTask()
    {
        //no webclient? no justice
        if (_webClient == null) return 100;

        //check if the shift changed, and if it did, react accordingly
        var currentShift = GetCurrentShift();
        if (_lastShift != currentShift)
        {
            foreach (var resetUrl in _resetUrls)
            {
                _webClient.DownloadString(resetUrl);
            }
        }
        //cache it because, well, we need to
        _lastShift = currentShift;
        return 5000;
    }

    private int GetCurrentShift()
    {
        var shift1End = Context.DataservTaglist.Tag("TAGGROUP::Dataserv Environment Items::TAG::Shift1End24h").Value as string;
        var shift2End = Context.DataservTaglist.Tag("TAGGROUP::Dataserv Environment Items::TAG::Shift2End24h").Value as string;
        var shift3End = Context.DataservTaglist.Tag("TAGGROUP::Dataserv Environment Items::TAG::Shift3End24h").Value as string;

        var shift1EndDateTime = DateTime.ParseExact(shift1End, "HHmm", CultureInfo.InvariantCulture);
        var shift2EndDateTime = DateTime.ParseExact(shift2End, "HHmm", CultureInfo.InvariantCulture);
        var shift3EndDateTime = DateTime.ParseExact(shift3End, "HHmm", CultureInfo.InvariantCulture);

        var shiftTimes = new[] { shift1EndDateTime, shift2EndDateTime, shift3EndDateTime };
        var indices = shiftTimes.ToDictionary(time => time.TimeOfDay, time => Array.IndexOf(shiftTimes, time) + 1);
        //sort the array, so that the "earliest" shift is first
        shiftTimes = shiftTimes.OrderBy(time => time).ToArray();
        //prepend/append the 'first/last' shift time the day before
        shiftTimes = shiftTimes.Append(shiftTimes.First().AddDays(1)).Prepend(shiftTimes.Last().AddDays(-1)).ToArray();
        //locate where we currently are in the shift
        for (var i = 0; i < shiftTimes.Length - 1; i++)
        {
            var shiftStart = shiftTimes[i];
            var shiftEnd = shiftTimes[i + 1];
            var now = DateTime.Now;

            if (shiftStart > shiftEnd && (now > shiftStart || now < shiftEnd) || now > shiftStart && now < shiftEnd)
            {
                return indices[shiftEnd.TimeOfDay];
            }
        }
        return -1;
    }
}