from plone import api
from ploneintranet.workspace.tests.base import BaseTestCase
from slc.mailrouter.interfaces import IFriendlyNameStorage
from slc.mailrouter.utils import store_name
from zope.component import queryUtility


class TestAdvancedSettings(BaseTestCase):
    def create_workspace(self, ws_id="example-workspace"):
        workspace_folder = api.content.create(
            self.workspace_container,
            "ploneintranet.workspace.workspacefolder",
            ws_id,
            title="Welcome to my workspace",
        )
        return workspace_folder

    def test_leave_email_empty(self):
        workspace = self.create_workspace()
        # In the actual instance email is initially None
        workspace.email = None
        request = self.request.clone()
        request.form.update({"email": ""})
        request.method = "POST"
        advanced_settings = api.content.get_view(
            "sidebar.settings.advanced", workspace, request
        )
        advanced_settings()  # just make sure there's no error

    def test_clear_email_address(self):
        workspace = self.create_workspace()
        workspace.email = "example-workspace"
        store_name(workspace, "example-workspace")

        request = self.request.clone()
        request.form.update({"email": ""})
        request.method = "POST"
        advanced_settings = api.content.get_view(
            "sidebar.settings.advanced", workspace, request
        )
        advanced_settings()

        storage = queryUtility(IFriendlyNameStorage)
        self.assertIsNone(storage.get("example-workspace"))
