'''

This is a python component that sort input curves based on curves' middle points in Y axis  

Compent name: Sort Curve in Y
Input Parameter:
        Geometry(Type:Curve): The curves are needed to sort.
        Reverse(Type:Boolen): Whether reverse the output list.
Output:
        Geometey: Sorted curves
        
__author__ = "Liang Mayuqi"
__version__ = "2021.04.20"

'''  

import Rhino.Geometry as rg
        
        
def find_center(geometry):
  '''
  __name__: find_center
  __msg__: To find the center point of input curve; the center point are calculated by the average point of vertexes that generated by divide curve.
  __paras__: 
        geometry: Single curve that needed to find center point. 
  __return__: 
        point: Center point.
  '''
    tValue_list = geometry.DivideByCount(100,True)
    point_list = [geometry.PointAt(t) for t in tValue_list]
    length = len(point_list)
    average_x = sum([point.X for point in point_list])/length
    average_y = sum([point.Y for point in point_list])/length
    average_z = sum([point.Z for point in point_list])/length
    return rg.Point3d(average_x,average_y,average_z)
        
        
def sort_list_object(list):
  '''
  __name__: sort_list_object
  __msg__: Sort one index list based on point.Y list; and then access curves list with sorted index list. 
  __paras__: 
        geometry: Curves that needed to sorted in Y Axis. 
  __return__: 
        curve list: Sorted curves list.
  '''
    length = len(list)
    index_list = [i for i in range(length)]
    center_point_list = [find_center(item) for item in list]
    Y_value = [point.Y for point in center_point_list]
    sorted_index = [index_list for Y_value, index_list in sorted(zip(Y_value, index_list))]
    sorted_geometry = [list[i] for i in sorted_index]
    return sorted_geometry
        
if Reverse == True:
    Geometry = sort_list_object(Geometry)[::-1]
else:
    Geometry = sort_list_object(Geometry)
