using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace GMLC01HerramientasCad.Acad
{

    public class TreeViewState
    {
        List<bool?> pLista;
        TreeNode pTopNode;

        public void SaveTreeView(TreeView treeView)
        {
            try
            {
                List<bool?> list = new List<bool?>();
                pTopNode = treeView.TopNode;
                SaveTreeViewExpandedState(treeView.Nodes, list);
                pLista = list;
            }
            catch (System.Exception ex)
            {
                Log.RegisterError(ex);
                throw new NotImplementedException("", ex);
            }
        }

        private int restoreTreeViewIndex;

        public void RestoreTreeView(TreeView treeView)
        {
            try
            {
                restoreTreeViewIndex = 0;
                RestoreTreeViewExpandedState(treeView.Nodes, pLista);
                if (pTopNode != null)
                    treeView.TopNode = pTopNode;
            }
            catch (System.Exception ex)
            {
                Log.RegisterError(ex);
                throw new NotImplementedException("", ex);
            }
        }

        private void SaveTreeViewExpandedState(TreeNodeCollection nodes, List<bool?> list)
        {
            foreach (TreeNode node in nodes)
            {
                list.Add(node.IsExpanded);
                if (node.Nodes.Count > 0)
                {
                    SaveTreeViewExpandedState(node.Nodes, list);
                }
            }
        }

        private void RestoreTreeViewExpandedState(TreeNodeCollection nodes, List<bool?> list)
        {
            if (list != null)
            {
                foreach (TreeNode node in nodes)
                {
                    if (restoreTreeViewIndex >= list.Count) break;

                    if (list[restoreTreeViewIndex++].Value)
                        node.Expand();
                    else
                        node.Collapse();

                    if (node.Nodes.Count > 0)
                    {
                        RestoreTreeViewExpandedState(node.Nodes, list);
                    }
                }
            }
        }
    }
}
