from Products.CMFCore.utils import getToolByName

from StringIO import StringIO
from types import InstanceType

from Products.intelligenttext.mimetype import text_web_intelligent

def registerMimeType(self, out, mimetype):
    if type(mimetype) != InstanceType:
        mimetype = mimetype()
    mimetypes_registry = getToolByName(self, 'mimetypes_registry')
    mimetypes_registry.register(mimetype)
    print >> out, "Registered mimetype", mimetype

def unregisterMimeType(self, out, mimetype):
    if type(mimetype) != InstanceType:
        mimetype = mimetype()
    mimetypes_registry = getToolByName(self, 'mimetypes_registry')
    mimetypes_registry.unregister(mimetype)
    print >> out, "Unregistered mimetype", mimetype

def registerTransform(self, out, name, module):
    transforms = getToolByName(self, 'portal_transforms')
    transforms.manage_addTransform(name, module)
    print >> out, "Registered transform", name

def unregisterTransform(self, out, name):
    transforms = getToolByName(self, 'portal_transforms')
    try:
        transforms.unregisterTransform(name)
        print >> out, "Removed transform", name
    except AttributeError:
        print >> out, "Could not remove transform", name, "(not found)"
    

def install(self):

    out = StringIO()

    print >> out, "Installing text/web-intelligent mimetype and transform"
                  
    # Register mimetype
    registerMimeType(self, out, text_web_intelligent)
                  
    # Register transforms
    registerTransform(self, out, 'web_intelligent_plain_text_to_html', 'Products.intelligenttext.transforms.web_intelligent_plain_text_to_html')
    registerTransform(self, out, 'html_to_web_intelligent_plain_text', 'Products.intelligenttext.transforms.html_to_web_intelligent_plain_text')

    return out.getvalue()
    
def uninstall(self):
    
    out = StringIO()
    
    # Remove transforms
    unregisterTransform(self, out, 'web_intelligent_plain_text_to_html')
    unregisterTransform(self, out, 'html_to_web_intelligent_plain_text')
    
    # Remove mimetype
    unregisterMimeType(self, out, text_web_intelligent)
    
    return out.getvalue()