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

namespace Eugen.ESystem.Windows.Forms
{
    internal class LoadXML
    {
        public string FileName { get; set; }
        public string Topic { get; set; } //z.B. "NX-Portal"
        public string Group { get; set; } //z.B. "Tools"
        public string[] Keys { get; set; } //z.B. "CleanUp"
        public string[] Values { get; set; } //z.B. "M:\ug\Tools\CleanUp\CleanUp.exe"
        public string[] Attributes { get; set; } //z.B. ""

        public void Load()
        {
            // Das Dokument in eine neue XElement-Instanz laden
            XElement rootElement = XElement.Load(FileName);

            // Auflistung für die Gruppe erzeugen
            List<Topics> groups = new List<Topics>();

            //Alle groups-Elemente einlesen und durchgehen
            //var personElements = rootElement.Elements(Group);
            var groupElements = rootElement.Elements();

            int i = 0;
            string[] temp = new string[5];
            List<string> lkeys = new List<string>();
            List<string> lvalues = new List<string>();
            List<string> lattributes = new List<string>();

            foreach (var groupElement in groupElements)
            {
                temp = groupElement.ToString().Split(' ');

                if (String.IsNullOrEmpty(Group))
                {
                    Group = ExtractGroup(temp);
                }
                lkeys.Add(ExtractKey(temp));
                lvalues.Add(ExtractValue(temp));
                lattributes.Add(ExtractAttribute(temp));

                i++;
            }

            string[] keys = new string[lkeys.Count];
            string[] values = new string[lvalues.Count];
            string[] attributes = new string[lattributes.Count];

            for (int j = 0; j < lkeys.Count; j++)
            {
                keys[j] = lkeys[j];
                values[j] = lvalues[j];
                attributes[j] = lattributes[j];
            }

            Keys = keys;
            Values = values;
            Attributes = attributes;
        }

        private string ExtractGroup(string[] temp)
        {
           return temp[0].Remove(0, 1);
        }

        private string ExtractKey(string[] temp)
        {
            return temp[1].Remove(temp[1].IndexOf("="));
        }

        private string ExtractValue(string[] temp)
        {
            return temp[1].Remove(0, temp[1].IndexOf("=") + 1).Replace("\"", "");
        }

        private string ExtractAttribute(string[] temp)
        {
            return temp[2].Remove(0, temp[2].IndexOf("=") + 1).Replace("\"", "");
        }
    }

    class Topics
    {
        public string Key;
        public string Value;
        public string Attribut;
    }
}
