using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using JWH;

namespace DDUtilityApp.WORKFLOW.DATA
{
    public class Flowchart
    {

        public List<Parameter> Variables { get; set; } = new List<Parameter>();

        public ViewState ViewState { get; set; }

        public FlowBase StartNode { get; set; }

        public string DisplayName { get; set; }

        public Flowchart()
        {
        }

        public Flowchart(XmlNode root)
        {
            //this.DisplayName = root.Attributes[$"DisplayName"].Value;
            foreach(XmlAttribute attribute in root.Attributes)
                if (string.Compare(attribute.Name, "DisplayName", true) == 0) this.DisplayName = attribute.Value;

            // Variables
            XmlNode nodeVariables = root.GetSingleNodeByName($"Flowchart.Variables");
            if (nodeVariables != null)
            {
                Parameter[] variables = this.GetVariables(nodeVariables);
                if (variables.Length > 0) this.Variables.AddRange(variables);
            }

            // ViewState
            XmlNode nodeViewState = root.GetSingleNodeByName($"sap:WorkflowViewStateService.ViewState");
            if (nodeViewState != null) this.ViewState = new ViewState(nodeViewState);

        }

        private Parameter[] GetVariables(XmlNode node)
        {
            List<Parameter> lstVariables = new List<Parameter>();
            foreach (XmlNode nodeVariable in node.ChildNodes)
            {
                if (string.Compare(nodeVariable.Name, "Variable", true) != 0) continue;

                Parameter variable = new Parameter(nodeVariable);
                if (variable != null) lstVariables.Add(variable);
            }

            return lstVariables.ToArray();
        }

    }
}
