using ReportingServices.Shared.Models.ProductionReport;

namespace ReportingServices.Shared.ViewModels.ProductionReport
{
    public class ToolStateByType
    {
        public int DownTools { get; set; }
        public int UpTools { get; set; }
        public List<ToolStateCurrent> ToolStateCurrents { get; set; }
        public List<string> ToolsDownGreaterThan12Hours { get; set; }

        public ToolStateByType(List<ToolStateCurrent> toolStateCurrents)
        {
            ToolStateCurrents = toolStateCurrents;
            ToolsDownGreaterThan12Hours = new List<string>();
            UpTools = 0;
            DownTools = 0;

            GetToolsDownGreaterThan12Hours();
            GetMostRecentTransactions();
            DetermineUpAndDownTools();
        }

        public void GetMostRecentTransactions()
        {
            for (int i = ToolStateCurrents.Count - 2; i >= 0; i--)
            {
                if (ToolStateCurrents[i].Tool == ToolStateCurrents[i + 1].Tool)
                    ToolStateCurrents.RemoveAt(i);
            }
        }

        public void GetToolsDownGreaterThan12Hours()
        {
            float elapsedTime = 0f;

            if (ToolStateCurrents[^1].BasicStateDescription.ToUpper() is not "PRODUCTIVE" and not "OUT OF SERVICE")
                float.Parse(ToolStateCurrents[^1].GanttElapsedHours);

            for (int i = ToolStateCurrents.Count - 2; i >= 0; i--)
            {
                if (ToolStateCurrents[i].Tool == ToolStateCurrents[i + 1].Tool)
                {
                    if (ToolStateCurrents[i].BasicStateDescription.ToUpper() != "PRODUCTIVE" && ToolStateCurrents[^1].BasicStateDescription.ToUpper() != "OUT OF SERVICE")
                        elapsedTime += float.Parse(ToolStateCurrents[i].GanttElapsedHours);
                }
                else
                {
                    if (elapsedTime >= 12)
                        ToolsDownGreaterThan12Hours.Add(ToolStateCurrents[i + 1].Tool);

                    if (ToolStateCurrents[i].BasicStateDescription.ToUpper() != "PRODUCTIVE" && ToolStateCurrents[^1].BasicStateDescription.ToUpper() != "OUT OF SERVICE")
                        elapsedTime = float.Parse(ToolStateCurrents[i].GanttElapsedHours);
                    else
                        elapsedTime = 0;
                }
            }
        }

        public void DetermineUpAndDownTools()
        {
            foreach (ToolStateCurrent tools in ToolStateCurrents)
            {
                if (tools.BasicStateDescription == "Productive")
                    UpTools++;
                else if (tools.ReactorStatus != "Out of Service")
                    DownTools++;
            }
        }
    }
}
