
import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino, copy

def CommandLineOptions(prompt,msg,ini,limits):
    #limits=[[True,tol],["No","Yes"]]
    #ini=[user_e_side,True]
    gn = Rhino.Input.Custom.GetNumber()
    gn.SetCommandPrompt(prompt)
    gn.SetLowerLimit(limits[0][1],False) #False: can equal limit
    
    blnOption0 = Rhino.Input.Custom.OptionToggle(ini[1],limits[1][0],limits[1][1])
    gn.AddOptionToggle(msg[1],blnOption0)
    gn.SetDefaultNumber(ini[0])
    n=ini[0]
    while True:
        get_rc = gn.Get()
        a=blnOption0.CurrentValue
        if gn.CommandResult()== Rhino.Commands.Result.Cancel:
            return
        elif gn.CommandResult()== Rhino.Commands.Result.Nothing:
            break
        elif get_rc==Rhino.Input.GetResult.Option:
            continue
        elif get_rc==Rhino.Input.GetResult.Number:
            n=gn.Number()
        break
    return (n,a)


def SweepPipe(path_crv, s_profile,e_profile,tol):   
    s_param=path_crv.Domain.T0
    e_param=path_crv.Domain.T1
    frames=path_crv.GetPerpendicularFrames([s_param,e_param])
    shapes=[]
    wxy=Rhino.Geometry.Plane.WorldXY
    xform=Rhino.Geometry.Transform.PlaneToPlane(wxy,frames[0])
    sp=copy.copy(s_profile)
    sp.Transform(xform)
    shapes.append(sp)
    xform=Rhino.Geometry.Transform.PlaneToPlane(wxy,frames[1])
    ep=copy.copy(e_profile)
    ep.Transform(xform)
    shapes.append(ep)
    brep=Rhino.Geometry.Brep.CreateFromSweep(path_crv,shapes,True,tol)
    return brep

def MultisquarePipe2V():
    tol=sc.doc.ModelAbsoluteTolerance
    crvs=rs.GetObjects("Select curves to square pipe",4,preselect=True)
    if not crvs: return
    
    if "MSP_StartSideLen" in sc.sticky: user_s_side = sc.sticky["MSP_StartSideLen"]
    else: user_s_side = 1.0
    
    s_side=rs.GetReal("Start side length",user_s_side,tol)
    if s_side is None: return
    
    if "MSP_EndSideLen" in sc.sticky: user_e_side = sc.sticky["MSP_EndSideLen"]
    else: user_e_side = s_side
    
    if "MSP_CapEnds" in sc.sticky: user_cap = sc.sticky["MSP_CapEnds"]
    else: user_cap = True
    
    prompt="End side length (0 for pipe to a point)"
    msg=["Length","CapEnds"]
    ini=[user_e_side,True]
    #allowing 0 as limit for end size allows pipe to a point...!
    limits=[[True,0],["No","Yes"]]
    result=CommandLineOptions(prompt,msg,ini,limits)
    if result: e_side,cap=result
    else: return
    
    interval=Rhino.Geometry.Interval(-s_side/2,s_side/2)
    s_rectangle=Rhino.Geometry.Rectangle3d(rs.WorldXYPlane(),interval,interval)
    s_square=s_rectangle.ToNurbsCurve()
    
    interval=Rhino.Geometry.Interval(-e_side/2,e_side/2)
    e_rectangle=Rhino.Geometry.Rectangle3d(rs.WorldXYPlane(),interval,interval)
    e_square=e_rectangle.ToNurbsCurve()
    
    rs.EnableRedraw(False)
    polyline_fail=0
    other_fail=0
    pipe_IDs=[]
    for crv in crvs:
        path_crv=sc.doc.Objects.Find(crv).Geometry
        pipe_brep=SweepPipe(path_crv,s_square,e_square,tol)
        if pipe_brep:
            if len(pipe_brep)>1:
                #polylines with different start/end sizes will fail
                if path_crv.IsPolyline(): polyline_fail+=1
                #other curves might fail also
                else: other_fail+=1
            else:
                #cap holes if set
                if cap: pipe_brep[0]=pipe_brep[0].CapPlanarHoles(tol)
                pipe_ID=sc.doc.Objects.AddBrep(pipe_brep[0])
                if pipe_ID: pipe_IDs.append(pipe_ID)
    sc.doc.Views.Redraw()
    sc.sticky["MSP_StartSideLen"] = s_side
    sc.sticky["MSP_EndSideLen"] = e_side
    sc.sticky["MSP_CapEnds"] = cap
    
    #reporting
    failed=polyline_fail+other_fail
    msg="Created {} square pipes on {} curves. ".format(len(crvs)-failed,len(crvs))
    if failed>0: msg+="  {} curves failed to pipe correctly.".format(failed)
    print msg
   
MultisquarePipe2V()

