from .update_social import UpdateSocialHandler
from plone import api
from ploneintranet import api as piapi
from ploneintranet.microblog.interfaces import IMicroblogTool
from ploneintranet.microblog.statusupdate import StatusUpdate
from zope.component import queryUtility

import logging

logger = logging.getLogger(__name__)


class CommentWellSaidView(UpdateSocialHandler):
    """
    Helper view that handles HTTP POST of update-social
    and renders a new update-social + the created post
    for injection back into the calling view.
    """

    @property
    def parent(self) -> StatusUpdate:
        container = queryUtility(IMicroblogTool)
        try:
            return container.get(self.request.get("post_id"))
        except KeyError:
            return container.get(self.request.get("container_id"))

    @property
    def postbox(self):
        """Find the context for the post box,
        which is the post that gave origin to the request
        """
        container = queryUtility(IMicroblogTool)
        try:
            context = container.get(self.request.get("post_id"))
            view_name = "update-social.html"
        except KeyError:
            context = container.get(self.request.get("container_id")).comments[
                int(self.request.get("post_id"))
            ]
            view_name = "add-reply-to-reply"
        return api.content.get_view(view_name, context, self.request)

    @property
    def render_post(self):
        """Ciao"""
        container = queryUtility(IMicroblogTool)
        if not self.post:
            return None
        try:
            container.get(self.post.id)
            view_name = "comment.html"
        except KeyError:
            view_name = "subcomment"
        return api.content.get_view(view_name, self.post, self.request)

    def init_post(self):
        post_details = {
            "text": self.post_text,
            "microblog_context": self.microblog_context,
            "mention_ids": self.post_mentions,
            "tags": self.post_tags,
        }

        # this is the post we are commenting
        post_id = self.request.form.get("post_id", None)

        container = queryUtility(IMicroblogTool)
        try:
            post = container.get(int(post_id))
        except KeyError:
            post = None

        if post is None or post.thread_id:
            parent = self.parent
            post_details["thread_id"] = self.parent.id
            post = parent.add_comment(**post_details)
            return post

        # post is a first level post
        post_details["thread_id"] = post.id
        return piapi.microblog.statusupdate.create(**post_details)
