// Copyright © Selmo Technology GmbH. All Rights Reserved

using Novus.Shared.Types.IssueHandling;

namespace SelmoStudio.Hmi.Server.SelmoHmi.Shared.Service
{
    internal class OperationResultIssuesService : IOperationResultIssuesService
    {
        private IReadOnlyList<Severity> _severities;

        public event EventHandler<ProcessedIssuesArgs> OnIssuesProcessed;

        public void Init(IReadOnlyList<Severity> severities)
        {
            _severities = severities;
        }

        public async Task ProcessIssuesAsync(IReadOnlyList<Issue> issues)
        {
            if (issues.Select(i => i.Severity).Distinct().Intersect(_severities).Any())
            {
                var wellKnownIssues = new List<Issue>();
                var unknownIssueOccured = false;

                foreach (var issue in issues)
                {
                    if (IssueIsWellKnown(issue.Id))
                    {
                        wellKnownIssues.Add(issue);
                    }
                    else
                    {
                        unknownIssueOccured = true;
                    }
                }

                OnIssuesProcessed?.Invoke(this, new ProcessedIssuesArgs(wellKnownIssues, unknownIssueOccured));
            }
        }

        private bool IssueIsWellKnown(IssueId id)
        {
            return _wellknownIssues.Contains(id);
        }

        #region Wellknown issues

        private static IssueId WellknownTestIssue1 { get; } = new(Guid.Parse("528fbbbb-76a9-45d5-9799-e22e098bb364"));
        private static IssueId WellknownTestIssue2 { get; } = new(Guid.Parse("f47f4fb3-4aaa-4236-bc1d-ae8d4716c051"));

        private static HashSet<IssueId> _wellknownIssues = new HashSet<IssueId>()
        {
            WellknownTestIssue1,
            WellknownTestIssue2
        };

        #endregion Wellknown issues
    }
}