/*******************************************************************************
  * Copyright (C) 2015 AgGateway and ADAPT Contributors
  * Copyright (C) 2015 Deere and Company
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
  * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> 
  *
  * Contributors:
  *    Tarak Reddy, Tim Shearouse - initial API and implementation
  *******************************************************************************/

using System;
using System.Collections.Generic;

namespace AgGateway.ADAPT.Representation.UnitSystem
{
    public class UnitOfMeasureCollection : UnitCollection<UnitOfMeasure>
    {
        public override UnitOfMeasure this[string domainId]
        {
            get
            {
                if (string.IsNullOrEmpty(domainId))
                    return null;

                var unitOfMeasure = base[domainId] ?? CreateCompositeUnitOfMeasure(domainId);
                if(unitOfMeasure == null)
                    throw new ArgumentOutOfRangeException();
                return unitOfMeasure;
            }
        }

        public UnitOfMeasureCollection()
            : this(new List<UnitOfMeasure>())
        {
            
        }

        public UnitOfMeasureCollection(IEnumerable<UnitOfMeasure> unitOfMeasures)
            : base(unitOfMeasures)
        {

        }

        private CompositeUnitOfMeasure CreateCompositeUnitOfMeasure(string domainId)
        {
            var unitOfMeasure = new CompositeUnitOfMeasure(domainId);
            AddCompositeUnitOfMeasure(domainId, unitOfMeasure);
            return unitOfMeasure;
        }

        private void AddCompositeUnitOfMeasure(string domainId, CompositeUnitOfMeasure unitOfMeasure)
        {
            Add(domainId, unitOfMeasure);
            foreach (var component in unitOfMeasure.Components)
                Add(component.DomainID, component.Unit);
        }
    }
}
