using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TreeViewControl
{
	public partial class Form1 : Form
	{
		private bool canCheckProcess = true;

		public Form1()
		{
			InitializeComponent();
			InitInstance();
		}

		private void InitInstance()
		{
			treeView.ImageList = imageList;

			TreeNode mainNode = new TreeNode("메인", 0, 2);
			mainNode.Nodes.Add("BE", "소고기", 0, 2);
			mainNode.Nodes.Add("PO", "돼지고기", 0, 2);
			mainNode.Nodes.Add("CH", "닭고기", 0, 2);
			mainNode.Nodes["BE"].Nodes.Add("KO", "한국산", 0, 2);
			mainNode.Nodes["BE"].Nodes.Add("US", "미국산", 0, 2);
			mainNode.Nodes["BE"].Nodes.Add("AU", "호주산", 0, 2);

			TreeNode subNode = new TreeNode("서브", 1, 2);
			subNode.Nodes.Add("BA", "구이", 1, 2);
			subNode.Nodes.Add("FR", "튀김", 1, 2);
			subNode.Nodes.Add("BO", "수육", 1, 2);

			treeView.Nodes.Add(mainNode);
			treeView.Nodes.Add(subNode);

			treeView.ExpandAll();
		}

		private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
		{
			string nodeKey = e.Node.Name;
			if (string.IsNullOrEmpty(nodeKey))
				return;

			Debug.WriteLine($"Key: {nodeKey}");
		}

		private void doButton_Click(object sender, EventArgs e)
		{
			List<TreeNode> checkedList = new List<TreeNode>();
			foreach (TreeNode node in treeView.Nodes)
			{
				if (node.Checked)
				{
					checkedList.Add(node);

					Debug.WriteLine($"Key: {node.Name}");
				}
			}
		}

		private void treeView_AfterCheck(object sender, TreeViewEventArgs e)
		{
			if (canCheckProcess)
			{
				canCheckProcess = false;

				CheckChildNode(e.Node, e.Node.Checked);
				CheckParentNode(e.Node, e.Node.Checked);

				canCheckProcess = true;
			}
		}

		private void CheckChildNode(TreeNode node, bool check)
		{
			foreach (TreeNode childNode in node.Nodes)
			{
				childNode.Checked = check;
				CheckChildNode(childNode, check);
			}

			node.Checked = check;
		}

		private void CheckParentNode(TreeNode node, bool check)
		{
			if (node.Parent == null)
				return;

			bool isAllNodeChecked = true;
			foreach (TreeNode childNode in node.Parent.Nodes)
			{
				if (childNode.Checked == false)
				{
					isAllNodeChecked = false;
					break;
				}
			}

			node.Parent.Checked = isAllNodeChecked;
			CheckParentNode(node.Parent, isAllNodeChecked);
		}
	}
}
