from ploneintranet.attachments.attachments import IAttachmentStoragable
from ploneintranet.attachments.attachments import IAttachmentStorage
from ploneintranet.attachments.testing import IntegrationTestCase
from zope.component import createObject
from zope.container.interfaces import DuplicateIDError
from zope.interface import alsoProvides


class TestAttachmentStorage(IntegrationTestCase):
    """Test the IAttachmentStorage adapter"""

    def test_add(self):
        """ """
        doc1 = createObject("Document")
        alsoProvides(doc1, IAttachmentStoragable)
        attachments = IAttachmentStorage(doc1)
        self.assertEqual(len(list(attachments.keys())), 0)
        self.assertEqual(len(list(attachments.values())), 0)
        f = createObject("File", id="data.dat")
        attachments.add(f)
        self.assertEqual([k for k in attachments.keys()], [f.getId()])
        self.assertEqual([v for v in attachments.values()], [f])

        # DuplicateIDError is thrown when an object with the same id is
        # added again.
        self.assertRaises(DuplicateIDError, attachments.add, f)

        i = createObject("Image", id="image.jpg")
        attachments.add(i)
        self.assertEqual(len(list(attachments.keys())), 2)
        self.assertEqual(len(list(attachments.values())), 2)
        self.assertIn(i.getId(), list(attachments.keys()))
        self.assertIn(i, list(attachments.values()))

    def test_remove(self):
        """ """
        question = createObject("Document")
        alsoProvides(question, IAttachmentStoragable)
        attachments = IAttachmentStorage(question)
        self.assertEqual(len(list(attachments.keys())), 0)
        self.assertEqual(len(list(attachments.values())), 0)
        for fname in ["data1.dat", "data2.dat"]:
            attachments.add(createObject("File", id=fname))
        self.assertEqual(len(list(attachments.keys())), 2)
        self.assertEqual(len(list(attachments.values())), 2)

        self.assertRaises(KeyError, attachments.remove, "data3.dat")

        attachments.remove("data1.dat")
        self.assertEqual(len(list(attachments.keys())), 1)
        self.assertIn("data2.dat", list(attachments.keys()))
        attachments.remove("data2.dat")
        self.assertEqual(len(list(attachments.keys())), 0)
