from gi.repository import Gtk, Adw, GLib
from giara.left_stack import LeftStack
from giara.post_details_view import PostDetailsView
from giara.confManager import ConfManager
from giara.accel_manager import add_mouse_button_accel
from praw.models import Comment, Message
from threading import Thread


class MainDeck(Adw.Bin):
    def __init__(self):
        super().__init__(vexpand=True)
        self._leaflet = Adw.Leaflet(
            vexpand=True, can_unfold=False, can_navigate_back=True,
            can_navigate_forward=False
        )
        self.set_child(self._leaflet)
        self.append = self._leaflet.append
        self.remove = self._leaflet.remove

        self.set_visible_child = self._leaflet.set_visible_child
        self.confman = ConfManager()
        self.reddit = self.confman.reddit

        self.left_stack = LeftStack(self.show_post)
        self.post_view_container = None
        self.append(self.left_stack)
        self.left_stack.set_size_request(300, 100)
        self._loading = False

    def show_post(self, post):
        if self._loading:
            return
        self._loading = True
        if isinstance(post, Message):
            return

        if self.post_view_container is not None:
            self.remove(self.post_view_container)
        self.post_view_container = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL
        )
        self.append(self.post_view_container)

        def on_mouse_event(gesture, n_press, x, y):
            if gesture.get_current_button() == 8:  # Mouse back btn
                self.go_back()

        def af(post):
            target_comment = None
            if isinstance(post, Comment):
                target_comment = post
                post = post.submission
            post._fetch()
            post.comments
            GLib.idle_add(cb, post, target_comment)

        def cb(post, target_comment):
            details_view = PostDetailsView(
                post, self.go_back, target_comment=target_comment
            )
            details_view.mouse_btn_accel = add_mouse_button_accel(
                details_view, on_mouse_event
            )
            self.post_view_container.append(details_view)
            self.set_visible_child(self.post_view_container)
            details_view.show()
            self._loading = False

        Thread(target=af, args=(post,), daemon=True).start()

    def go_back(self):
        self.set_visible_child(self.left_stack)
