import Rhino
import scriptcontext
import rhinoscriptsyntax as rs

def DoCircleTTT():

    rc_main = rs.GetCurveObject("Select main curve", False, False)
    if not rc_main: return

    rc_crv_1 = rs.GetCurveObject("Select first curve to trim with arc", False, False)
    if not rc_crv_1: return

    rc_crv_2 = rs.GetCurveObject("Select second curve to trim with arc", False, False)
    if not rc_crv_2: return
    
    # find the 3 curve parameters required for TryFitCircleTTT
    # the parameters on the curves to trim are the pick point parameters
    param_1 = rc_crv_1[4]
    param_2 = rc_crv_2[4]
    
    # the parameter on the curve which is not trimmed is in between p1 and p2
    # get the closest point on main curve near the midpoint of p1 and p2
    mid_pt = (rc_crv_1[3] + rc_crv_2[3]) * 0.5
    param_main = rs.CurveClosestPoint(rc_main[0], mid_pt, segment_index = -1)
    
    # convert the curve objects to RhinoCommon curves first
    c0 = rs.coercecurve(rc_main[0], -1, True)
    c1 = rs.coercecurve(rc_crv_1[0], -1, True)
    c2 = rs.coercecurve(rc_crv_2[0], -1, True)
    
    # try to fit a circle using the 3 curves and 3 parameters with RhinoCommon
    circle = Rhino.Geometry.Circle.TryFitCircleTTT(c0, c1, c2, param_main, param_1, param_2)
    if circle == Rhino.Geometry.Circle.Unset:
        print "No circle created"
        return None
    
    id = scriptcontext.doc.Objects.AddCircle(circle)
    if id: 
        scriptcontext.doc.Views.Redraw()
        rs.SelectObject(id)
        # Todo: trim c1 and c2 at circle intersection points...

if __name__=="__main__":
    DoCircleTTT()