from ploneintranet.notifications.sql import saconfig
from ploneintranet.workspace.utils import parent_workspace


class CreatedInWorkspaceFactory:
    def __call__(self, obj, event):
        if obj.portal_type not in ("Document", "File"):
            return

        workspace = parent_workspace(obj)
        if not workspace:
            return

        saconfig.log_event(obj, "workspace_content", {"event_type": "created"})


class PublishedInWorkspaceFactory:
    def __call__(self, obj, event):
        if obj.portal_type not in ("Document", "File"):
            return

        workspace = parent_workspace(obj)
        if not workspace:
            return

        if event.new_state == event.old_state or event.new_state.title != "Published":
            return

        saconfig.log_event(obj, "workspace_content", {"event_type": "published"})


log_created_in_workspace = CreatedInWorkspaceFactory()
log_published_in_workspace = PublishedInWorkspaceFactory()
