"""
HB_SmoothEdgeEnter V1.1

Last Modified: 1/1/2016
Works with CINEMA 4D R16.050 and up.
Copyright: Holger Biebrach, www.c4dstuff.com

Name-US: HB_SmoothEdgeConvert
Description-US: Converts the SmoothEdge Setup into a Polygonal Mesh

Video Tutorial:
https://youtu.be/Ki6I9sRdeUU?t=28m16s


ChangeLog:
1/1/2016 v1.1
- Python Rewrite
- Support for Retopo Workflow

6/11/2015 v1.0
Release Version

"""

import c4d
from c4d import gui, utils


def RemoveChildren(objlist):
    
    for obj in objlist:
        doc.AddUndo(c4d.UNDOTYPE_DELETE, obj)
        obj.Remove()
        
    
    c4d.EventAdd()    
    return

def InsertChildren(objlist,root):
    for obj in objlist:
        
        if obj.GetName() != "HB_Modify_Spline" and obj.GetName() != "HB_Orginal_Spline" and obj.GetName() != "HB_Smoothedge_Deformer" :
            doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj)
            obj.InsertUnder(root)
            print "yes"
        
    c4d.EventAdd()    
    return




def deletetags(obj): # Scan Tags on Object
    
    n       = 1 
    
    tags    = obj.GetTags()

    for tag in tags:
        if not tag: continue
        tagtype = tag.GetType()
        #count   = checktype(tags).count(tagtype)       
        
        
        if tag.GetName()=="smoothedge-restriction":
            doc.AddUndo(c4d.UNDOTYPE_DELETE, tag)
            tag.Remove()
            c4d.EventAdd()

  

def main():
    doc.StartUndo()
    
    
    
    if not doc.GetActiveObject():
        gui.MessageDialog("Select SmoothEdge Mesh or Modifying Spline!")
        return
    
    selobj=doc.GetActiveObject()
    
    if selobj.GetName() == "HB_Modify_Spline":
        print "spline selected"
        selobj = selobj.GetUp()
        print selobj.GetName()

  
    children = selobj.GetChildren()

  
       
        
    selobjpos=selobj.GetMg()
    
    
    CSsettings = c4d.BaseContainer()                 
    NewObj=utils.SendModelingCommand(command = c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                            list = [selobj],
                            mode = c4d.MODELINGCOMMANDMODE_EDGESELECTION,
                            bc = CSsettings,
                            doc = doc,
                            )
                            
    
    
    if NewObj[0].GetType()==c4d.Onull:
        NewObjChild=NewObj[0].GetDown()
        NewObjChild.InsertAfter(selobj)
        doc.AddUndo(c4d.UNDOTYPE_NEW, NewObjChild)
    else:
        NewObjChild=NewObj[0]
        NewObjChild.InsertAfter(selobj)
        doc.AddUndo(c4d.UNDOTYPE_NEW, NewObjChild)
        RemoveChildren(NewObjChild.GetChildren())
        
        
    
    
  
    
    doc.AddUndo(c4d.UNDOTYPE_DELETE, selobj)
    selobj.Remove()
    
    
 

        
    InsertChildren(children,NewObjChild)              
    deletetags(NewObjChild)
    doc.AddUndo(c4d.UNDOTYPE_BITS, NewObjChild)
    NewObjChild.SetBit(c4d.BIT_ACTIVE)

    
        
    
    c4d.EventAdd()
    doc.EndUndo()



if __name__=='__main__':
    main()
