// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace Microsoft.Data.Entity.Design.Model.Mapping
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Xml.Linq;
    using Microsoft.Data.Entity.Design.Model.Entity;

    internal class FunctionComplexProperty : EFElement
    {
        internal static readonly string ElementName = "ComplexProperty";

        internal static readonly string AttributeName = "Name";
        internal static readonly string AttributeTypeName = "TypeName";

        private SingleItemBinding<ComplexConceptualProperty> _property;
        private SingleItemBinding<ComplexType> _complexType;

        private readonly List<FunctionScalarProperty> _scalarProperties = new List<FunctionScalarProperty>();
        private readonly List<FunctionComplexProperty> _complexProperties = new List<FunctionComplexProperty>();

        internal FunctionComplexProperty(EFElement parent, XElement element)
            : base(parent, element)
        {
        }

        internal override string EFTypeName
        {
            get { return ElementName; }
        }

        internal SingleItemBinding<ComplexConceptualProperty> Name
        {
            get
            {
                if (_property == null)
                {
                    _property = new SingleItemBinding<ComplexConceptualProperty>(
                        this,
                        AttributeName,
                        FunctionPropertyMappingNameNormalizer.NameNormalizer
                        );
                }
                return _property;
            }
        }

        internal SingleItemBinding<ComplexType> TypeName
        {
            get
            {
                if (_complexType == null)
                {
                    _complexType = new SingleItemBinding<ComplexType>(
                        this,
                        AttributeTypeName,
                        EFNormalizableItemDefaults.DefaultNameNormalizerForMSL
                        );
                }
                return _complexType;
            }
        }

        internal void AddScalarProperty(FunctionScalarProperty prop)
        {
            _scalarProperties.Add(prop);
        }

        internal void AddComplexProperty(FunctionComplexProperty prop)
        {
            _complexProperties.Add(prop);
        }

        internal IList<FunctionScalarProperty> ScalarProperties()
        {
            return _scalarProperties.AsReadOnly();
        }

        internal IList<FunctionComplexProperty> ComplexProperties()
        {
            return _complexProperties.AsReadOnly();
        }

        internal FunctionComplexProperty FindFunctionComplexProperty(Property property)
        {
            foreach (var fcp in _complexProperties)
            {
                if (fcp.Name.Target == property)
                {
                    return fcp;
                }
            }

            return null;
        }

        protected override void OnChildDeleted(EFContainer efContainer)
        {
            var sp = efContainer as FunctionScalarProperty;
            if (sp != null)
            {
                _scalarProperties.Remove(sp);
                return;
            }

            var cp = efContainer as FunctionComplexProperty;
            if (cp != null)
            {
                _complexProperties.Remove(cp);
                return;
            }

            base.OnChildDeleted(efContainer);
        }

        // we unfortunately get a warning from the compiler when we use the "base" keyword in "iterator" types generated by using the
        // "yield return" keyword.  By adding this method, I was able to get around this.  Unfortunately, I wasn't able to figure out
        // a way to implement this once and have derived classes share the implementation (since the "base" keyword is resolved at 
        // compile-time and not at runtime.
        private IEnumerable<EFObject> BaseChildren
        {
            get { return base.Children; }
        }

        internal override IEnumerable<EFObject> Children
        {
            get
            {
                foreach (var efobj in BaseChildren)
                {
                    yield return efobj;
                }

                foreach (var child in ScalarProperties())
                {
                    yield return child;
                }

                foreach (var child2 in ComplexProperties())
                {
                    yield return child2;
                }

                yield return Name;
                yield return TypeName;
            }
        }

#if DEBUG
        internal override ICollection<string> MyAttributeNames()
        {
            var s = base.MyAttributeNames();
            s.Add(AttributeName);
            s.Add(AttributeTypeName);
            return s;
        }
#endif

#if DEBUG
        internal override ICollection<string> MyChildElementNames()
        {
            var s = base.MyChildElementNames();
            s.Add(ScalarProperty.ElementName);
            s.Add(ComplexProperty.ElementName);
            return s;
        }
#endif

        protected override void PreParse()
        {
            Debug.Assert(State != EFElementState.Parsed, "this object should not already be in the parsed state");

            ClearEFObject(_property);
            _property = null;

            ClearEFObject(_complexType);
            _complexType = null;

            ClearEFObjectCollection(_scalarProperties);
            ClearEFObjectCollection(_complexProperties);

            base.PreParse();
        }

        internal override bool ParseSingleElement(ICollection<XName> unprocessedElements, XElement elem)
        {
            if (elem.Name.LocalName == FunctionScalarProperty.ElementName)
            {
                var prop = new FunctionScalarProperty(this, elem);
                _scalarProperties.Add(prop);
                prop.Parse(unprocessedElements);
            }
            else if (elem.Name.LocalName == ElementName)
            {
                var complexProperty = new FunctionComplexProperty(this, elem);
                _complexProperties.Add(complexProperty);
                complexProperty.Parse(unprocessedElements);
            }
            else
            {
                return base.ParseSingleElement(unprocessedElements, elem);
            }
            return true;
        }

        protected override void DoResolve(EFArtifactSet artifactSet)
        {
            Name.Rebind();
            TypeName.Rebind();

            if (Name.Status == BindingStatus.Known
                && TypeName.Status == BindingStatus.Known)
            {
                State = EFElementState.Resolved;
            }
        }

        internal override void GetXLinqInsertPosition(EFElement child, out XNode insertAt, out bool insertBefore)
        {
            /// 557417: push these to the top so that they are always before any ResultBinding elements
            if (child is FunctionScalarProperty)
            {
                insertAt = FirstChildXElementOrNull();
                insertBefore = true;
            }
            else
            {
                base.GetXLinqInsertPosition(child, out insertAt, out insertBefore);
            }
        }
    }
}
