using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Valg.EVA.Skanning.Entity.ReadModel;

namespace Valg.EVA.Skanning.ServicesModel.Internal.Verification
{
    public class BallotPaperFieldValueAggregate
    {
        public static List<BallotPaperFieldValueAggregate> CreateListOfAggregates(List<BallotPaperFieldValue> originalFieldValues, ReadOnlyCollection<BallotPaperFieldValue> currentFieldValues)
        {
            var aggregates = new List<BallotPaperFieldValueAggregate>();

            foreach (var originalFieldValue in originalFieldValues)
            {
                aggregates.Add(new BallotPaperFieldValueAggregate { OriginalValue = originalFieldValue });
            }

            foreach (var currentFieldValue in currentFieldValues)
            {
                var existing = aggregates.FirstOrDefault(a => a.OriginalValue != null 
                                                              && a.OriginalValue.FieldType == currentFieldValue.FieldType
                                                              && a.OriginalValue.FieldIndex == currentFieldValue.FieldIndex);

                if (existing != null)
                {
                    existing.CurrentValue = currentFieldValue;
                }
                else
                {
                    aggregates.Add(new BallotPaperFieldValueAggregate { CurrentValue = currentFieldValue });
                }
            }

            return aggregates;
        }

        public BallotPaperFieldValue CurrentValue { get; set; }

        public BallotPaperFieldValue OriginalValue { get; set; }

        public string GetOriginalValueIfPresent()
        {
            if (OriginalValue != null)
                return OriginalValue.Value;

            return null;
        }

        public bool DidOriginalValueNeedVerification()
        {
            return OriginalValue != null && OriginalValue.NeedsVerification;
        }
    }
}
