import System
import clr
import templatetools

from Ansys.ACT.Interfaces.Common import *
from Ansys.ACT.Interfaces.Geometry import *
from Ansys.ACT.Interfaces.Mesh import *

def IsInFilter(prop, values):
    if len(values) == 0: return False
    filters = templatetools.ParseFilter(prop.Attributes["selection_filter"])
    allValueAreInFilter = True
    for v in values:
        if not v in filters:
            allValueAreInFilter = False
            break
    return allValueAreInFilter

def IsSelectionValid(prop, selection):
    """
    Check if the given selection is valid.
    """
    if selection == None: return False
    if not prop.Attributes["selection_filter"]: return True

    nB = selection.Bodies.Count
    nF = selection.Faces.Count
    nE = selection.Edges.Count

    filters = []
    if nB>0 : filters.Add("body")
    if nF>0 : filters.Add("face")
    if nE>0 : filters.Add("edge")

    return IsInFilter(prop, filters)

class GeometryObj:

    def __init__(self, api, entity, prop):
        self.api = api
        self.entity = entity
        self.prop = prop

    def onapply(self, entity, prop):
        selection = self.api.SelectionManager.CurrentSelection
        if IsSelectionValid(prop, selection):
            prop.Value = selection

    def value2string(self, entity, prop, val):
        if val == None or val.Entities.Count == 0:
            return "None"

        txt = ""
        if val.Bodies.Count != 0:
            txt += 'Bodies ( {0} ) '.format(val.Bodies.Count)
        if val.Faces.Count != 0:
            txt += 'Faces ( {0} ) '.format(val.Faces.Count)
        if val.Edges.Count != 0:
            txt += 'Edges ( {0} ) '.format(val.Edges.Count)

        return txt
