from cStringIO import StringIO
from Products.CMFCore.DirectoryView import addDirectoryViews
from Products.CMFCore.utils import getToolByName
from Products.PloneErrorReporting import error_reporting_globals

def install(self):
    """Register the error_reporting skin"""
    out = StringIO()
    installSkins(self, out)
    return out.getvalue()

def uninstall(portal):
    out = StringIO()
    uninstallSkins(portal, out)
    return out.getvalue()


def installSkins(portal, out):
    # Setup the skins
    skins_tool = getToolByName(portal, 'portal_skins')
    if 'plone_error_reporting' not in skins_tool.objectIds():
        addDirectoryViews(skins_tool, 'skins', error_reporting_globals)
        out.write("Added 'PloneErrorReporting.skins' directory view to portal_skins\n")

    skins = skins_tool.getSkinSelections()
    for skin in skins:
        path = skins_tool.getSkinPath(skin)
        path = [p.strip() for p in path.split(',') if p]
        if 'plone_error_reporting' not in path:
            if path:
                path.insert(1, 'plone_error_reporting')
            else:
                path.insert(0, 'plone_error_reporting')
        skins_tool.addSkinSelection(skin, ','.join(path))

    print >> out, 'Installed plone_error_reporting layer to skins'


def uninstallSkins(portal, out):
    skins_tool = getToolByName(portal, 'portal_skins')

    skins = skins_tool.getSkinSelections()
    for skin in skins:
        path = skins_tool.getSkinPath(skin)
        path = [p.strip() for p in path.split(',') if p]
        while 'plone_error_reporting' in path:
            path.remove('plone_error_reporting')
        skins_tool.addSkinSelection(skin, ','.join(path))

    print >> out, 'Removed plone_error_reporting layer from skins'