import transaction
from Products.CMFCore.utils import getToolByName
from ftw.cmissync.operations import Update, Delete, Move, Rename
from ftw.cmissync.datamanager import DataManager
from ftw.cmissync.config import TYPE_FIELD_MAPPINGS


def update(obj, event):
    """
    """
    portal_type = obj.portal_type

    # Do nothing if no mapping has been defined for this type
    if portal_type not in TYPE_FIELD_MAPPINGS:
        return

    transaction.get().join(DataManager(Update(obj)))


def move(obj, event):
    """
    """
    # Don't deal with unfinished Archetypes objects
    if obj.checkCreationFlag():
        return

    # Deleting
    if event.newParent is None:
        portal_url = getToolByName(obj, 'portal_url')
        path = '/'.join(portal_url.getRelativeContentPath(obj))
        transaction.get().join(DataManager(Delete(path)))

    # Moving, Renaming
    elif event.oldParent is not None and event.newParent is not None:
        # Ignore renaming of objects with an autogenerated id
        putils = getToolByName(obj, 'plone_utils')
        if putils.isIDAutoGenerated(event.oldName):
            return

        # Moving
        if event.oldParent is not event.newParent:
            portal_url = getToolByName(obj, 'portal_url')
            obj_path = '/'.join(portal_url.getRelativeContentPath(obj))
            target_folder_path = '/'.join(portal_url.getRelativeContentPath(event.newParent))
            transaction.get().join(DataManager(Move(obj_path, target_folder_path)))

        # Renaming
        else:
            portal_url = getToolByName(obj, 'portal_url')
            old_path = '/'.join(portal_url.getRelativeContentPath(obj))
            transaction.get().join(DataManager(Rename(old_path, event.newName)))


def copy(obj, event):
    if event.newParent is not None and event.oldParent is None:
        transaction.get().join(DataManager(Update(obj)))
