using System;
using System.Collections;
using System.Collections.Specialized;

using ms.aq.cview.util;

namespace ms.aq.cview.query {
    /*
     * token collections should not be manipulated directly, but through this instead.
     */
    public abstract class TokenCollectionManager {
        /**
         * Creates a hashtable, where each key is a hierarchy,
         * and each value is an ArrayList containing all tokens that
         * reference that hierarchy
         */
        public static Hashtable CreateHierarchyMap(ref SelectionSets ss) {
            Hashtable rst;
            StringCollection allTokens = ss.GetAllTokens();
            CollapseHierarchies(ref allTokens, out rst);
            return rst;
        }
        public static string GetHierarchyUID(string uid) {
            return uid;
        }
        private static void CollapseHierarchies(ref StringCollection sc, out Hashtable rst) {
            string hid = null;
            rst = new Hashtable();
            foreach (string piece in sc) {
                string[] tokens = piece.Split(':');
                ArrayList tmp = null;
                hid = GetHierarchyUID(piece);
                if (!rst.ContainsKey(hid))
                    rst[hid] = new ArrayList();
                tmp = (ArrayList)rst[hid];
                tmp.Add(piece);
                rst[hid] = tmp;
            }
        }
        public static string DerangeToken(string s) {
            return s.Split(':')[0];
        }
        private static string CollectionContainsHierarchy(string token, StringCollection sc) {
            try {
                StringCollection tmp = common.UID2Tokens(token);
                string h = tmp[0] + "." + tmp[1];
                foreach (string s in sc) {
                    if (s.IndexOf(h) > -1)
                        return s;
                }
                return null;
            }
            catch {
                throw new Exception(token);
            }
        }
        private static void ExpandCollection(table_cube_interface tci, string token, ref StringCollection sc) {
            MaybeRemove(tci, token, ref sc);
            sc.Add(token);
        }
        private static void MaybeRemove(table_cube_interface tci, string token, ref StringCollection sc) {
            string s = CollectionContainsHierarchy(token, sc);
            if (s == null) return;
            VHierarchy vh = tci.GetHierarchy(s);
            if (vh.Type == VHType.DEEP)
                sc.Remove(s);
        }
        private static void ShrinkCollection(string token, ref StringCollection sc) {
            if (token.CompareTo("CLEAR_THIS_AXIS") == 0) {
                sc.Clear();
                return;
            }
            sc.Remove(token);
        }
    }
}