import rhinoscriptsyntax as rs
import scriptcontext as sc
from Rhino import RhinoMath
    
def SelMeshesByArea():
    objs=rs.ObjectsByType(32,state=1)
    if not objs: return
    tol=sc.doc.ModelAbsoluteTolerance
    ff=tol #"fuzz factor" #meshes need larger fuzz factor
    entity="mesh"
    measure="area"
    cl=["LessThan","GreaterThan","EqualTo","LTorEqualTo","GTorEqualTo","Between"]
    
    #get previous settings
    if "SMA_Type_Choice" in sc.sticky: type_choice = sc.sticky["SMA_Type_Choice"]
    else: type_choice = cl[0]
    if "SMA_User_A" in sc.sticky: user_A = sc.sticky["SMA_User_A"]
    else: user_A = 1.0
    if "SMA_Max_A" in sc.sticky: max_A = sc.sticky["SMA_Max_A"]
    else: max_A = 1.0
    if "SMA_Min_A" in sc.sticky: min_A = sc.sticky["SMA_Min_A"]
    else: min_A = 1.0
    
    rs.UnselectAllObjects()
    msg="Selection type for {} {}?".format(entity,measure)
    while True:
        compare=rs.GetString(msg,type_choice,cl)
        if not compare: return
        if compare in cl: break
    
    if compare == cl[5]:
        min_A=rs.GetReal("Minimum area?",min_A,minimum=tol)
        if not min_A: return
        if max_A<min_A: max_A=min_A
        max_A=rs.GetReal("Maximum area?",max_A,minimum=min_A)
        if not max_A: return
    else:
        area=rs.GetReal("Area?",user_A,minimum=tol)
        if not area: return
        
    rs.EnableRedraw(False)
    for obj in objs:
        ma=rs.MeshArea(obj)
        if not ma: continue
        obj_area=ma[1]
        if compare==cl[0]:
            if obj_area < area-ff: rs.SelectObject(obj)
        elif compare==cl[1]:
            if obj_area > area+ff: rs.SelectObject(obj)
        elif compare==cl[2]:
            if abs(area-obj_area)<ff: rs.SelectObject(obj)
        elif compare==cl[3]:
            if obj_area <= area: rs.SelectObject(obj)
        elif compare==cl[4]:
            if obj_area >= area: rs.SelectObject(obj)
        elif compare==cl[5]:
            if obj_area >= min_A and obj_area <= max_A: rs.SelectObject(obj)
            
    selObjs=rs.SelectedObjects()
    if selObjs:
        q=len(selObjs)
        if q>1: entity+="es"
    else: q="No" ; entity+="es"
    print "{} {} found that match selection criteria".format(q,entity)
    
    #store previous settings
    sc.sticky["SMA_Type_Choice"] = compare
    try: sc.sticky["SMA_User_A"] = area
    except: pass
    try: sc.sticky["SMA_Max_A"] = max_A
    except: pass
    try: sc.sticky["SMA_Min_A"] = min_A
    except: pass
SelMeshesByArea()
