from logging import getLogger
from plone import api
from plone.memoize import forever
from plone.memoize.view import memoize
from plone.namedfile.file import NamedBlobImage
from ploneintranet import api as pi_api
from ploneintranet.contacts.content.contact import IEmergencyServiceMarker
from ploneintranet.core import _
from ploneintranet.workspace.browser.add_content import AddBase
from zope.container.interfaces import INameChooser
from zope.interface import alsoProvides
from zope.interface.exceptions import Invalid
from zope.schema.vocabulary import getVocabularyRegistry

logger = getLogger(__name__)


class PanelAddGroup(AddBase):
    """Add a workgroup"""

    panel_instance = "panel-create-group-division"
    _form_data_pat_inject_parts = (
        "#document-body",
        "#sidebar-content",
        "#global-statusmessage; loading-class: ''",
    )

    @property
    def tabs(self):
        tabs = []
        if self.app_view.can_add_contacts:
            tabs.extend(
                [
                    # TODO: Implement "All contacts"
                    # {
                    #    "id": "sheet-contact",
                    #    "css_class": "icon-user current",
                    #    "label": _(u"Contact"),
                    # },
                    {
                        "id": "sheet-emergency-service",
                        "css_class": "icon-alarm",
                        "label": _("Emergency service"),
                    },
                ]
            )
        if self.app_view.can_add_workgroups:
            tabs.append(
                {
                    "id": "sheet-user-group",
                    "css_class": "icon-users",
                    "label": _("User group"),
                }
            )
        return tabs

    @property
    def title(self):
        if self.app_view.can_add_contacts:
            if self.app_view.can_add_workgroups:
                return _("Create group or contact")
            else:
                return _("Create contact")
        elif self.app_view.can_add_workgroups:
            return _("Create group")

    @property
    @memoize
    def app_view(self):
        return api.content.get_view(
            name="app-contacts", context=self.context, request=self.request
        )

    @property
    @forever.memoize
    def service_icons(self):
        """Return the ploneintranet.layout.manyicons vocabulary"""
        vr = getVocabularyRegistry()
        return vr.get(self.context, "ploneintranet.layout.manyicons")

    @property
    def portal_type(self):
        return self.request.form.get("portal_type", "")

    def get_new_unique_id(self, container):
        """
        This will get a new unique id according to the request. Overwritten from
        the base class, since we have our own special method for suggesting an id.
        """

        def get(key, default=None):
            return self.request.form.get(key, default)

        suggested_id = (
            get("name", "")
            or (
                " ".join(
                    name
                    for name in (
                        get("first_name", ""),
                        get("last_name", ""),
                    )
                    if name
                )
            )
            or get("company", "")
        )

        chooser = INameChooser(container)
        new_id = chooser.chooseName(suggested_id, container)
        return new_id

    def create_group(self):
        form = self.request.form
        kw = {
            key: form.get(key, "")
            for key in ("canonical", "description", "members", "title")
        }
        properties = kw["properties"] = {}
        image = form.get("image")
        if image:
            properties["image"] = NamedBlobImage(
                data=image.read(), filename=image.filename
            )
        if kw["members"]:
            kw["members"] = kw["members"].split(",")
        else:
            kw["members"] = []

        group = pi_api.workgroup.create(**kw)
        return group

    def update(self, obj):
        result = super().update(obj)
        if self.request.get("contact_type", "") == "emergency-service":
            alsoProvides(obj, IEmergencyServiceMarker)
        return result

    def __call__(self):
        if not self.is_posting():
            self.maybe_disable_diazo()
            return self.index()
        if self.portal_type == "ploneintranet.userprofile.workgroup":
            try:
                group = self.create_group()
                url = group.absolute_url()
            except (ValueError, Invalid):
                return self.index()
        elif self.portal_type == "ploneintranet.contacts.contact":
            container = api.portal.get().contacts
            url = self.create(container)
        else:
            logger.info(f"Unexpected portal_type {self.portal_type}")
            api.portal.show_message(
                message="There was an error, please try again.",
                request=self.request,
                type="error",
            )
            url = self.context.absolute_url()
        return self.redirect(url)
