# -*- coding: utf-8 -*-
"""
CleanTreeTool + 自动命名组件
将 CleanTree_Py 封装为类，并增加自动命名功能：

新增功能：
- 将输入端 Tree 的“连接名称”作为当前组件名称的一部分：
    若输入 Tree 的源对象名称为 "FooBar"
    则组件自动命名为：
        CleanTree_FooBar
"""

import System
import Grasshopper as gh
from Grasshopper import DataTree
from Grasshopper.Kernel.Data import GH_Path
import Grasshopper.Kernel.Types as ght


class CleanTreeTool(object):
    """可复用的 GH DataTree Clean 工具"""

    @staticmethod
    def is_null_or_invalid(x):
        """判断为 Null / Invalid / 空对象"""

        if x is None:
            return True

        if isinstance(x, str) and x == "":
            return True

        if isinstance(x, (list, tuple)) and len(x) == 0:
            return True

        if isinstance(x, ght.IGH_Goo):
            try:
                if hasattr(x, "IsNull") and x.IsNull:
                    return True
                if hasattr(x, "IsValid") and (not x.IsValid):
                    return True
            except:
                pass

            try:
                v = x.Value
                if hasattr(v, "IsValid") and (not v.IsValid):
                    return True
            except:
                pass

            return False

        if hasattr(x, "IsValid"):
            try:
                if x.IsValid is False:
                    return True
            except:
                pass

        return False

    # -------------------------------------------------

    @staticmethod
    def clean(tree_in):
        """执行完整 CleanTree 等效清理"""
        if tree_in is None:
            return None

        new_tree = DataTree[object]()

        try:
            all_paths = tree_in.Paths
        except:
            return None

        for path in all_paths:
            try:
                branch = list(tree_in.Branch(path))
            except:
                branch = []

            valid_items = [
                item for item in branch
                if not CleanTreeTool.is_null_or_invalid(item)
            ]

            if len(valid_items) == 0:
                continue

            for v in valid_items:
                new_tree.Add(v, path)

        return new_tree


# ============================================================
# 🔥 新增功能：自动将 Tree 的输入名称作为当前组件名称
# ============================================================

def auto_set_component_name():
    """
    将组件名称自动设置为：
        CleanTree_<InputName>

    InputName = 输入端 Tree 的来源名称（例如 Panel 名称、Upstream 组件输出名称）
    """
    try:
        inp = ghenv.Component.Params.Input[0]   # 第 0 个输入端为 Tree
        srcs = inp.Sources                      # 获取所有连接源

        if srcs is None or len(srcs) == 0:
            # 无连接 → 不修改组件名
            return

        # 取第一个连接源
        src = srcs[0]

        # 若来源是组件 → 使用它的输出端名称
        name = getattr(src, "NickName", None) or getattr(src, "Name", None)

        if not name or name.strip() == "":
            return

        # 设置组件名称
        new_name = "CleanTree_" + name
        ghenv.Component.Name = new_name
        ghenv.Component.NickName = new_name

    except Exception as e:
        print("自动命名失败:", e)

if __name__ == "__main__":
    # ============================================================
    # 组件主要执行
    # ============================================================

    # 先执行自动命名
    auto_set_component_name()

    # 再执行清理功能
    if Tree is None:
        Tree_Cleaned = None
    else:
        Tree_Cleaned = CleanTreeTool.clean(Tree)
