"""
@package CurveReader.hcurve_creator
Creates curves based on data loaded by the loader
@author Coen Klosters
@version 1.0
"""

import hou

class CurveCreator(object):
    """
    Load those damn things in Houdini
    """
    
    def __init__(self, inCurveLoader):
        """
        Based on the data in the curve loader, create 'm
        @param inCurveLoader: The curve loader to extract data from
        """
        
        self.Loader = inCurveLoader
        
        # holds the houdini node that is created for the curves
        self.CurveContainer = None
        
        # holds the node that merges all the curves
        self.CurveMerger = None
        
        
        
    def CreateCurves(self):
        """
        Creates all the curves and populates the object
        """
        
        if self.Loader.Points is None:
            raise Exception("Unable to query points for curve creation!")

        if self.Loader.Curves is None:
            raise Exception("Unable to query curve data for curve creation!")
        
        if self.Loader.UserInfo is None:
            raise Exception("Unable to extract user information for curve creation...")
        
        # Create the new curve container
        container_name =  self.Loader.UserInfo.FName
        self.CurveContainer = hou.node("/obj").createNode("geo","%s_curve_container" % container_name)
        for c in self.CurveContainer.children():
            c.destroy()
        
        # Create the curve merge node
        self.CurveMerger = self.CurveContainer.createNode("merge", "CurveMerger")
        
        # Add the curves
        count = 0
        for c in self.Loader.Curves:
            curve_node = self.CreateHoudiniCurve(c)
            self.CurveMerger.setInput(count, curve_node)
            count += 1
            
        # Make 'm lay in a good way
        self.CurveContainer.layoutChildren()
        self.CurveContainer.moveToGoodPosition()
        self.CurveContainer.setDisplayFlag(False)
        
        
        
    def CreateHoudiniCurve(self, inCurve):
        """
        Creates the houdini curve in the scene and returns it
        """
        
        node = self.CurveContainer.createNode("curve", "curve_%s" % inCurve.Number)
        points = []
        
        coordinates = ""
        for v in inCurve.Verts:
            sample_p = self.Loader.Points[v]
            point_coords = "%s,%s,%s " % (sample_p.Position[0], sample_p.Position[1], sample_p.Position[2])
            coordinates += point_coords

        node.parm("coords").set(coordinates)
        node.parm("type").set(1)
        node.parm("method").set(1)
        return node