#!/usr/bin/env python3

import json
import time
from urllib.parse import quote

import alt_media_player
import blog_tools
from bridge import AsyncBridge as Bridge
from browser import aio, document, window
from cache import identities, roster
import dialog
import editor
import jid
from jid_search import JidSearch
from tools import fuzzy_match
from panel_manager import PanelManager
from popup import create_popup
from template import Template
import uri

bridge = Bridge()
alt_media_player.install_if_needed()

libervia_data = window.libervia_data.to_dict()
own_jid = libervia_data.get("own_jid")
blog_url = libervia_data["blog_url"]
service = libervia_data["service"]
node = libervia_data["node"]
items_http_uri = libervia_data.get("items_http_uri") or {}


class LiberviaWebBlog:

    def __init__(self) -> None:
        # Initialize PanelManager
        self.panel_manager = PanelManager()
        self.editing_item_id = None
        self.editing_published = None
        self.followed = libervia_data.get("followed")

        self._init_new_post_panel()
        self._init_follow_button()

        try:
            contact_blogs_elt = document["contact-blogs"]
        except KeyError:
            pass
        else:
            self.contacts_links_tpl = Template("components/contacts_links.html")
            contacts_links_elt = self.contacts_links_tpl.get_elt(
                {"roster": roster, "identities": identities, "base_url": blog_url}
            )
            contact_blogs_elt <= contacts_links_elt
        # init after the contact blogs list is rendered, as the search field also filters
        # it
        self._init_blog_search()

        blog_tools.init_items(None, service, node, own_jid)
        blog_tools.init_commenting(own_jid)
        self.item_tpl = Template("blog/item.html")
        self._init_pagination()

    def _init_new_post_panel(self) -> None:
        """Set up the new post editor in the right panel.

        The panel is only in the page for logged-in users; do nothing otherwise.
        """
        if document.select_one("#editor") is None:
            return

        self.new_post_editor = editor.RichEditor("#editor")
        self.new_post_tags = editor.TagsEditor("#editor-tags")
        self.item_menu_tpl = Template("blog/item_menu.html")

        document["new-post-btn"].bind("click", self._on_new_post_click)
        document["editor-publish"].bind("click", self._on_publish_click)

        self._init_item_actions()

    def _init_blog_search(self) -> None:
        """Initialize the blog search field of the discovery panel."""
        search_elt = document.select_one(".search-input")
        if search_elt is None:
            return
        results_elt = document["blog-search-results"]
        self.search_elt = search_elt
        self.search_results_elt = results_elt
        JidSearch(
            search_elt,
            results_elt,
            get_url=self._get_blog_url,
            template="components/search_item.html",
            empty_cb=self.on_search_empty,
        )
        search_elt.bind("input", self._on_search_input)
        document.select_one(".action_clear_search").bind(
            "click", lambda __: self._clear_search()
        )
        # pre-compute the matchable texts of the contact blogs list (the list is only
        # present when a user is connected)
        self._contact_items = []
        contact_blogs_elt = document.select_one("#contact-blogs")
        if contact_blogs_elt is None:
            return
        for li in contact_blogs_elt.select("li"):
            a = li.select_one("a")
            name = a.select_one("p").text.strip().lower()
            jid_s = a["href"][len(blog_url) + 1 :].lower()
            self._contact_items.append((li, [name, jid_s]))

    def _clear_search(self) -> None:
        self.search_elt.value = ""
        self.search_elt.dispatchEvent(window.Event.new("input"))

    async def on_search_empty(self, jid_search: JidSearch) -> None:
        self.search_results_elt.clear()

    def _on_search_input(self, evt) -> None:
        """Filter the contact blogs list with the search term."""
        query = evt.target.value.strip().lower()
        for li, texts in self._contact_items:
            hidden = bool(query) and not any(fuzzy_match(query, t) for t in texts)
            li.classList.toggle("is-hidden", hidden)

    @staticmethod
    def _get_blog_url(item) -> str:
        return f"{blog_url}/{quote(item['entity'])}"

    def _init_follow_button(self) -> None:
        try:
            follow_button = document["follow-button"]
        except KeyError:
            return
        self.follow_btn_tpl = Template("blog/follow_button.html")
        follow_button.bind("click", self._on_follow_click)

    def _on_follow_click(self, evt) -> None:
        aio.run(self.toggle_follow())

    async def toggle_follow(self) -> None:
        """(Un)follow the displayed blog (pubsub subscription of its node).

        The button is disabled while the request is in progress, and is regenerated
        according to the new state (or an error is shown).
        """
        button = document["follow-button"]
        button.disabled = True
        try:
            if self.followed:
                await bridge.ps_unsubscribe(service, node)
            else:
                await bridge.ps_subscribe(service, node, "")
        except Exception as e:
            dialog.notification.show(f"Can't follow/unfollow: {e}", "error")
            button.disabled = False
            return
        self.followed = not self.followed
        new_button = self.follow_btn_tpl.get_elt({"followed": self.followed})
        new_button.bind("click", self._on_follow_click)
        button.replaceWith(new_button)

    def _init_item_actions(self, parent_elt=None) -> None:
        """Attach the edit/delete actions menu to the items.

        @param parent_elt: Parent of the items to update.
            If None, the whole document is used.
        """
        parent_elt = parent_elt or document
        for item_elt in parent_elt.select(".blog-item"):
            button_elt = item_elt.select_one("button.item-actions-button")
            button_elt.bind(
                "click",
                lambda evt, item_elt=item_elt: self._on_item_actions(evt, item_elt),
            )

    def _on_item_actions(self, evt, item_elt) -> None:
        """Open the actions menu of an item."""
        evt.stopPropagation()
        menu_elt = self.item_menu_tpl.get_elt()
        menu_popup = create_popup(evt.currentTarget, menu_elt, placement="top")

        own_jid_bare_s = str(jid.JID(own_jid).bare)
        if (
            item_elt.getAttribute("data-author") != own_jid_bare_s
            and item_elt.getAttribute("data-repeated-by") != own_jid_bare_s
        ):
            # The item is not from the current user, and it's not a repeat of it: hide the
            # "edit" and "delete" actions.
            for cls_name in ("action_edit", "action_delete"):
                for elt in menu_elt.select(f".{cls_name}"):
                    elt.remove()
        elif item_elt.hasAttribute("data-repeated-by"):
            # We don't show "edit" for repeated items.
            for elt in menu_elt.select(".action_edit"):
                elt.remove()

        def on_action_click(evt, callback):
            evt.preventDefault()
            menu_popup.hide()
            aio.run(callback(evt, item_elt))

        edit_cb = (
            blog_tools.edit_comment
            if item_elt.hasAttribute("data-comment")
            else self._on_item_edit
        )
        for cls_name, callback in (
            ("action_repeat", self._on_item_repeat),
            ("action_copy", self._on_item_copy),
            ("action_xmpp_uri", self._on_item_xmpp_uri),
            ("action_edit", edit_cb),
            ("action_delete", self._on_item_delete),
        ):
            for elt in menu_elt.select(f".{cls_name}"):
                elt.bind(
                    "click", lambda evt, callback=callback: on_action_click(evt, callback)
                )

    async def _on_item_repeat(self, evt, item_elt) -> None:
        """Repeat the item."""
        item_service, item_node = blog_tools.item_service_node(item_elt, service, node)
        try:
            await bridge.mb_repeat(item_service, item_node, item_elt.id, "")
        except Exception as e:
            dialog.notification.show(f"Can't repeat the item: {e}", "error")
        else:
            dialog.notification.show("Item repeated.")

    async def _copy_text(self, text, label) -> None:
        """Copy the given text to the clipboard"""
        try:
            window.navigator.clipboard.writeText(text)
        except Exception as e:
            dialog.notification.show(f"Can't copy the {label}: {e}", "error")
        else:
            dialog.notification.show(f"{label} copied.")

    async def _on_item_copy(self, evt, item_elt) -> None:
        """Copy the HTTP link of the item (parent post for comments)."""
        post_elt = blog_tools.item_post(item_elt)
        url = items_http_uri.get(post_elt.id) if post_elt is not None else None
        if url is None:
            dialog.notification.show("No link for this item.", "error")
            return
        await self._copy_text(url, "link")

    async def _on_item_xmpp_uri(self, evt, item_elt) -> None:
        """Copy the XMPP URI of the item."""
        item_service, item_node = blog_tools.item_service_node(item_elt, service, node)
        uri_s = uri.build_xmpp_uri(
            "pubsub", path=item_service, node=item_node, item=item_elt.id
        )
        await self._copy_text(uri_s, "XMPP URI")

    async def _on_item_edit(self, evt, item_elt) -> None:
        """Open the item with the rich editor."""
        self.editing_item_id = item_elt.id
        self.editing_published = float(item_elt["data-published"])
        self._set_editing_mode(True)
        title_elt = item_elt.select_one("h4.title")
        document["editor-title"].value = title_elt.text if title_elt else ""
        self.new_post_tags.clear()
        for tag_elt in item_elt.select(".labels .tag"):
            self.new_post_tags.add_tag(tag_elt.text, force=True)
        self.new_post_editor.set_content(item_elt.select_one(".item-content").html)
        self.panel_manager.on_toggle_click(evt, "right")

    async def _on_item_delete(self, evt, item_elt) -> None:
        """Delete the item, after confirmation."""
        confirmed = await dialog.Confirm(
            "This will be deleted, are you sure?", ok_label="delete"
        ).ashow()
        if not confirmed:
            return
        item_service, item_node = blog_tools.item_service_node(item_elt, service, node)
        try:
            await bridge.ps_item_retract(item_service, item_node, item_elt.id, True)
        except Exception as e:
            dialog.notification.show(f"Can't delete the item: {e}", "error")
        else:
            item_elt.remove()

    def _set_editing_mode(self, editing: bool) -> None:
        """Toggle the "new post" / "edit post" indicator in the panel."""
        document["editor-new-post-label"].hidden = editing
        document["editor-edit-post-label"].hidden = not editing

    def _on_new_post_click(self, evt) -> None:
        # This changes the default behaviour (which open an edit page with static editor).
        evt.preventDefault()
        self._reset_fields()
        self.editing_item_id = None
        self.editing_published = None
        self._set_editing_mode(False)
        self.panel_manager.on_toggle_click(evt, "right")

    def _on_publish_click(self, evt) -> None:
        evt.preventDefault()
        aio.run(self.do_publish())

    async def do_publish(self) -> None:
        """Publish the post"""
        text = self.new_post_editor.get_text().strip()
        if not text:
            dialog.notification.show("The post content is empty.", "error")
            return

        mb_data = {
            "service": service,
            "node": node,
            "content_xhtml": self.new_post_editor.get_clean_html(),
            "allow_comments": True,
        }
        if self.editing_item_id is not None:
            mb_data["id"] = self.editing_item_id
            mb_data["published"] = self.editing_published
            mb_data["updated"] = time.time()
        title = document["editor-title"].value.strip()
        if title:
            mb_data["title_rich"] = title
        if self.new_post_tags.current_tags:
            mb_data["tags"] = list(self.new_post_tags.current_tags)
        mentions = self.new_post_editor.get_mentions()
        if mentions:
            mb_data["mentions"] = mentions

        btn = document["editor-publish"]
        btn.classList.add("is-loading")
        try:
            await bridge.mb_send(json.dumps(mb_data))
        except Exception as e:
            dialog.notification.show(f"Can't publish the post: {e}", "error")
            btn.classList.remove("is-loading")
        else:
            self._reset_fields()
            window.location.reload()

    def _reset_fields(self) -> None:
        """Clear all editor fields."""
        document["editor-title"].value = ""
        self.new_post_tags.clear()
        self.new_post_editor.clear()

    def _init_pagination(self) -> None:
        """Make the pagination load pages dynamically."""
        try:
            self._page_num_elt = document["page-num"]
        except KeyError:
            return
        self._page_total_elt = document["page-total"]
        self._top_el = document.select_one("#pagination-top")
        if self._top_el is not None:
            # top pagination, hidden by default when on the first page
            self._top_num_elt = document["page-num-top"]
            self._top_total_elt = document["page-total-top"]
        self._loading_page = False
        for link in document.select(".pagination-previous, .pagination-next"):
            # bind all links, even the disabled ones, as their state changes dynamically
            link.bind("click", lambda evt, link=link: self._on_page_link(evt, link))
        window.bind("popstate", lambda _: window.location.reload())

    def _on_page_link(self, evt, link) -> None:
        """Navigate to the page behind a prev_next link."""
        evt.preventDefault()
        aio.run(self._fetch_page(link))

    async def _fetch_page(self, link) -> None:
        """Load the page behind a prev_next link, replacing the feed content."""
        if self._loading_page:
            return
        href = link.getAttribute("href")
        if not href:
            # disabled link
            return
        self._loading_page = True
        try:
            url = window.URL.new(href, window.location.href)
            extra = {
                "rsm_max": str(url.searchParams.get("page_max") or "10"),
                "order_by": "creation",
            }
            before = url.searchParams.get("before")
            if before:
                extra["rsm_before"] = str(before)
            else:
                after = url.searchParams.get("after")
                if after:
                    extra["rsm_after"] = str(after)
            data = json.loads(await bridge.mb_get(service, node, None, [], extra))
            self._render_items(data["items"])
            self._update_pagination(data.get("rsm"), data.get("complete"), url)
            window.history.pushState({}, "", url.toString())
            scroller = document["body"]
            if self._top_el is not None and self._top_el.contains(link):
                # clicked the top bar: back to the top, so it and the beginning of the new
                # page are visible
                scroller.scrollTop = 0
            else:
                # clicked the bottom bar: keep the bar at the bottom of the scroller
                nav_bottom = link.parent.getBoundingClientRect().bottom
                scroller.scrollTop = (
                    nav_bottom + scroller.scrollTop - scroller.clientHeight
                )
        except Exception as e:
            dialog.notification.show(f"Can't load the page: {e}", "error")
        finally:
            self._loading_page = False

    def _render_items(self, items) -> None:
        """Replace the feed content with the given items, and initialise it."""
        container = document.select_one("#blog_items .column")
        container.clear()
        # items are returned oldest first, display them newest first
        for mb_data in reversed(items):
            context = {
                "item": mb_data,
                "identities": identities,
                "dates_format": "short",
            }
            container <= self.item_tpl.get_elt(context)
        blog_tools.init_items(container, service, node, own_jid)
        self._init_item_actions(container)

    def _update_pagination(self, rsm, complete, url) -> None:
        """Update page indicators and prev_next links after a dynamic load."""
        page_max = int(str(url.searchParams.get("page_max") or "10"))
        base_url = window.URL.new(url.toString())
        base_url.searchParams.delete("before")
        base_url.searchParams.delete("after")
        if rsm is None or rsm.get("count") is None:
            return
        count, index = int(rsm["count"]), int(rsm.get("index", 0))
        num = (count - 1 - index) // page_max + 1
        total = max(1, (count + page_max - 1) // page_max)
        self._page_num_elt.text = str(num)
        self._page_total_elt.text = " / " + str(total)
        if self._top_el is not None:
            # only display the top pagination when not on the first page
            self._top_el.style.display = "block" if num > 1 else "none"
            if num > 1:
                self._top_num_elt.text = str(num)
                self._top_total_elt.text = " / " + str(total)
        for link in document.select(".pagination-previous"):
            self._set_page_link(link, index > 0, base_url, "before", rsm["first"])
        for link in document.select(".pagination-next"):
            self._set_page_link(link, not complete, base_url, "after", rsm["last"])

    def _set_page_link(self, link, enabled, base_url, param, item_id) -> None:
        """Set the state of a prev_next link."""
        disabled_classes = (
            "pagination-disabled",
            "has-text-grey-light",
            "has-hover-white-light",
        )
        if enabled:
            page_url = window.URL.new(base_url.toString())
            page_url.searchParams.set(param, item_id)
            link.href = page_url.toString()
            for cls in disabled_classes:
                link.classList.remove(cls)
        else:
            link.removeAttribute("href")
            for cls in disabled_classes:
                link.classList.add(cls)


libervia_web_blog = LiberviaWebBlog()
