"""
Functional test for content which requies access to mime types registry during
instance construction. The sample content type here is one generated by
ZopeSkel for a folder content type.
"""

from unittest import defaultTestLoader

import transaction

from zope.component import getUtility
from zope.event import notify
from zope.app.component.hooks import getSite, setSite

from ore.contentmirror import loader, interfaces, operation, schema
from ore.contentmirror.tests.mocker import MockerTestCase
from ore.contentmirror.ptests.base import MirrorTestCase

from Products.Archetypes import atapi
from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content import schemata
from Products.CMFCore.WorkflowCore import ActionSucceededEvent
from Products.CMFCore.interfaces import IWorkflowTool

ExampleTypeSchema = folder.ATFolderSchema.copy()
ExampleTypeSchema['title'].storage = atapi.AnnotationStorage()
ExampleTypeSchema['description'].storage = atapi.AnnotationStorage()
schemata.finalizeATCTSchema(
    ExampleTypeSchema,
    folderish=True,
    moveDiscussion=False)


class ExampleType(folder.ATFolder):
    """Description of the Example Type"""

    meta_type = "Example Type"
    schema = ExampleTypeSchema

    title = atapi.ATFieldProperty('title')
    description = atapi.ATFieldProperty('description')

    def __init__(self, *args, **kw):
        super(ExampleType, self).__init__(*args, **kw)


class ContentCreationTest(MockerTestCase, MirrorTestCase):

    def afterSetUp(self):
        """
        Remove any local sites so we recreate the environment
        in which content classes are loaded by content mirror.
        """
        local_site = getSite()
        # make sure tests are resetting environ
        self.assertTrue(local_site)
        setSite()
        self.addCleanup(setSite, local_site)

    def test_content_creation_exception(self):
        """
        Without the plone site as a local site manager attempting
        to create the content will raise an exception.
        """
        self.assertRaises(AttributeError, ExampleType, "doc-a")

    def test_content_load(self):
        loader.load(ExampleType)
        registry = getUtility(interfaces.IPeerRegistry)
        self.assertTrue(ExampleType in registry)


class ContentWorkflowTest(MockerTestCase, MirrorTestCase):

    def _create_content(self, id):
        self.loginAsPortalOwner()
        self.portal.invokeFactory("Document", id)
        transaction.commit()
        self.assertEqual(len(list(schema.content.select().execute())), 1)
        return self.portal[id]

    def test_content_workflow_event_generates_update(self):
        content = self._create_content("wf-test-1")
        event = ActionSucceededEvent(content, None, None, None)
        notify(event)
        ops = operation.get_buffer().ops.values()
        self.assertEqual(len(ops), 1)
        self.assertTrue(isinstance(ops[0],
                                   operation.UpdateOperation))


def test_suite():
    return defaultTestLoader.loadTestsFromName(__name__)
