using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using PXP.Crawler.API.Utils;

namespace PXP.Crawler.API.Model
{
    public class NodeConnectionProperty : NodeConnection
    {
        public PropertyInfo sourcePropInfo;
        public PropertyInfo targetPropInfo;

        public NodeConnectionProperty(Program program, Node sourceNode, Node targetNode, PropertyInfo sourcePropertyInfo, PropertyInfo targetPropertyInfo) : base(program, sourceNode, targetNode)
        {
            type = NodeConnectionType.PropertyProperty;
            sourcePropInfo = sourcePropertyInfo;
            targetPropInfo = targetPropertyInfo;
        }

        public override void Update()
        {
            base.Update();

            targetPropInfo.SetValue(target, sourcePropInfo.GetValue(source));
            target.NotifyPropertyChange(targetPropInfo.Name);
        }

        protected internal override void PutXml(XmlElement connElement)
        {
            base.PutXml(connElement);

            Misc.CreateAppendXmlElement(connElement, "src_pname", sourcePropInfo.Name);
            Misc.CreateAppendXmlElement(connElement, "targ_pname", targetPropInfo.Name);
        }

        public override void UpdateNodeReferences()
        {
            if (sourcePropInfo != null)
            {
                if (!source.outPropConns.ContainsKey(sourcePropInfo.Name))
                {
                    SortedDictionary<int, NodeConnectionProperty> outConns = new SortedDictionary<int, NodeConnectionProperty>();
                    outConns.Add(this.id, this);
                    source.outPropConns.Add(sourcePropInfo.Name, outConns);
                }
                if (!target.inPropConns.ContainsKey(sourcePropInfo.Name))
                {
                    if (targetPropInfo != null)
                    {
                        target.inPropConns.Add(sourcePropInfo.Name, this);
                        target.OnInputPinConnected(targetPropInfo.Name);
                    }
                }
                
            }
        }
    }
}
