from datetime import datetime
from plone import api
from ploneintranet.workspace.tests.base import BaseTestCase
from zope.component import getMultiAdapter


class TestArchiving(BaseTestCase):
    """
    Workspaces and Case Workspaces can be archived.
    """

    def setUp(self):
        super().setUp()
        self.catalog = api.portal.get_tool("portal_catalog")
        self.login_as_portal_owner()

        self.archived_workspace = api.content.create(
            self.portal.workspaces,
            "ploneintranet.workspace.workspacefolder",
            "archived-workspace",
            title="Archived Workspace",
            archival_date=datetime(2015, 12, 25),
        )
        self.unarchived_workspace = api.content.create(
            self.portal.workspaces,
            "ploneintranet.workspace.workspacefolder",
            "unarchived-workspace",
            title="Unarchived Workspace",
        )
        self.solr_commit()

    def get_search_titles(self, params):
        """Given some parameters, return a list of the search results titles"""
        request = self.request.clone()
        request.form.update(params)
        search_view = getMultiAdapter((self.portal, request), name="search")
        search_results = list(search_view.search_response())
        return [i.title for i in search_results]

    def test_archived_items_in_default_search_results(self):
        """
        Optionally includes the archived items
        """
        # Searches return by default skips archived items
        params = {"SearchableText": "Workspace"}
        result_titles = self.get_search_titles(params)
        self.assertFalse("Archived Workspace" in result_titles)
        self.assertTrue("Unarchived Workspace" in result_titles)

        # they can be included optionally
        params["include_archived"] = "1"
        result_titles = self.get_search_titles(params)
        self.assertTrue("Archived Workspace" in result_titles)
        self.assertTrue("Unarchived Workspace" in result_titles)
