using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using nft.framework.drawing;
using System.Drawing;
using nft.core.geometry;

namespace nft.impl.view_old {
    public class QVSpriteTree {
        private TreeElement elmRoot = new TreeElement(null, 0);
        public TreeElement Root { get { return elmRoot; } }
        public void Clear(bool disposeSprites) {
            if (disposeSprites) {
                foreach (TreeElement elm in Root.GetBottomUpEnumerator()) {
                    if (elm.sprite != null) {
                        elm.sprite.Dispose();
                    }
                    elm.children = null;
                }
            } else {
                elmRoot.children = null;
            }
        }
    }

    public class TreeElement {
        internal List<TreeElement> children = null;
        internal ISprite sprite;
        private Int32 z;

        public ISprite Sprite { get { return sprite; } }
        public Int32 ZValue { get { return z; } }
        //public Object Marker;
        internal TreeElement(ISprite s, Int32 z_val) {
            this.sprite = s;
            this.z = z_val;
        }

        public TreeElement AddChild(ISprite s, Int32 z_val) {
            if (children == null) {
                children = new List<TreeElement>();
            }
            TreeElement e = new TreeElement(s, z_val);
            children.Add(e);
            return e;
        }

        public void SortChildren() {
            if (children != null) {
                children.Sort(ElementCoparer.TheInstance);
            }
        }

        public int ChildCount {
            get { return (children == null) ? 0 : children.Count; }
        }

        public IEnumerable<TreeElement> GetBottomUpEnumerator() {
            if(children!=null){
                int n = children.Count-1;
                for(int i=n; i>=0; i--){
                    foreach (TreeElement elm in children[i].GetBottomUpEnumerator()) {
                        yield return elm;
                    }
                }
            }
            yield return this;
            yield break;
        }

        public IEnumerable<TreeElement> GetTopDownEnumerator() {
            yield return this;
            if (children != null) {
                int n = children.Count;
                for (int i = 0; i < n; i++) {
                    foreach (TreeElement elm in children[i].GetBottomUpEnumerator()) {
                        yield return elm;
                    }
                }
            }
            yield break;
        }

    }

    internal class ElementCoparer : IComparer<TreeElement> {
        #region IComparer<StackElement> メンバ
        public int Compare(TreeElement x, TreeElement y) {
            return x.ZValue - y.ZValue;
        }
        #endregion
        static public readonly ElementCoparer TheInstance = new ElementCoparer();
    }

}
