using JWH;
using System;
using System.Collections;
using System.Collections.Generic;

namespace DDUtilityApp.SECS
{


    static class SECSLib
    {

        public static Dictionary<string, Type> ItemFormat = new Dictionary<string, Type>()
        {
            { "L", typeof(IList) },     { "A", typeof(string) },    { "B", typeof(byte) },    { "BOOL", typeof(bool) },
            { "J", typeof(int) },       { "F4", typeof(float) },    { "F8", typeof(float) },
            { "I1", typeof(Int16) },    { "I2", typeof(Int16) },    { "I4", typeof(Int32) },    { "I8", typeof(Int64) },
            { "U1", typeof(UInt16) },   { "U2", typeof(UInt16) },   { "U4", typeof(UInt32) },   { "U8", typeof(UInt64) },
        };

        public enum ItemType { None, Format, Length, Name, Value }

        public static SECSItem[] GetItemByName(this SECSItem item, params string[] names)
        {
            List<SECSItem> items = new List<SECSItem>();

            foreach (string name in  names)
                if (string.Compare(item.Name, name, true) == 0) items.Add(item);

            foreach(SECSItem childItem in item)
                items.AddRange(childItem.GetItemByName(names));

            return items.ToArray();
        }

        public static SECSItem[] GetItemCPValue(this SECSItem item, params string[] names)
        {
            List<SECSItem> items = new List<SECSItem>();
            if (item.ChildItems.Count != 2) return items.ToArray();

            foreach (SECSItem childItem in item.ChildItems[1])
            {
                if (childItem.Format != "L") continue;
                if (childItem.ChildItems.Count != 2) continue;
                foreach(string name in names)
                {
                    if (string.Compare(childItem.ChildItems[0].Value, name, true) == 0)
                    {
                        items.Add(childItem.ChildItems[1]);
                        break;
                    }
                }
            }

            return items.ToArray();
        }

        public static SECSItem[] GetItemByID(this SECSItem item, string id)
        {
            List<SECSItem> items = new List<SECSItem>();

            if (string.Compare(item.ID, id, true) == 0) items.Add(item);
            foreach (SECSItem childItem in item)
                items.AddRange(childItem.GetItemByID(id));

            return items.ToArray();
        }

    }

}
