from giara.constants import RESOURCE_PREFIX
from gettext import gettext as _
from gi.repository import Gtk, GLib
from giara.simple_avatar import SimpleAvatar
from giara.path_utils import is_image
from giara.download_manager import download_img
from giara.time_utils import humanize_utc_timestamp
from giara.flair_label import FlairLabel, FlairTextColor
from giara.post_preview import PostPreviewListbox
from giara.giara_clamp import new_clamp
from giara.single_post_stream_headerbar import SinglePostStreamHeaderbar
from giara.markdown_view import MarkdownView
from giara.sections import SectionScrolledWindow
from praw.models import Comment, Submission
from threading import Thread


class InboxItemView(Gtk.Box):
    def __init__(self, item, **kwargs):
        super().__init__(**kwargs)
        self.get_style_context().add_class('card')
        self.get_style_context().add_class('activatable')
        self.item = item
        self.builder = Gtk.Builder.new_from_resource(
            f'{RESOURCE_PREFIX}/ui/inbox_item_view.ui'
        )
        self.main_box = self.builder.get_object('main_box')

        self.markdown_container = self.builder.get_object('markdown_container')
        self.markdown_view = MarkdownView(self.item.body)
        self.markdown_container.append(self.markdown_view)

        self.avatar_container = self.builder.get_object('avatar_container')
        self.avatar = SimpleAvatar(
            42,
            self.item.author.name if self.item.author else _('Author unknown'),
            self.get_author_img
        )
        self.avatar_container.append(self.avatar)
        self.author_label = self.builder.get_object('author_label')
        self.author_label.set_text(
            'u/' + self.item.author.name if self.item.author is not None
            else _('Author unknown')
        )

        def set_post_title_async():
            if isinstance(self.item, Comment):
                title = self.item.submission.title
                GLib.idle_add(set_post_title_cb, title)

        def set_post_title_cb(title):
            self.author_label.set_text(
                self.author_label.get_text() + '\n' +
                _('Comment in "{0}"').format(title)
            )

        Thread(target=set_post_title_async, daemon=True).start()

        self.datetime_label = self.builder.get_object('datetime_label')
        self.datetime_label.set_text(
            humanize_utc_timestamp(self.item.created_utc)
        )

        self.flairs_container = self.builder.get_object('flairs_container')
        self.flairs_container.append(
            FlairLabel.new_from_type(self.item)
        )
        self.new_flair = None
        if self.item.new:
            self.new_flair = FlairLabel(
                _('New'), '#33d17a', FlairTextColor.DARK
            )
            self.flairs_container.append(self.new_flair)
        else:
            self.mark_read()

        self.append(self.main_box)

    def get_author_img(self):
        if (
                self.item.author is not None and
                is_image(self.item.author.icon_img)
        ):
            download_img(self.item.author.icon_img)

    def mark_read(self):

        def af():
            self.item.mark_read()

        Thread(target=af, daemon=True).start()
        for w in (
                self.author_label, self.flairs_container,
                self.markdown_view, self.avatar_container
        ):
            w.get_style_context().add_class('dim-label')
        if self.new_flair is not None:
            self.flairs_container.remove(self.new_flair)
            self.new_flair = None


class InboxListboxRow(Gtk.ListBoxRow):
    def __init__(self, item, **kwargs):
        super().__init__(**kwargs)
        self.item = item
        self.post = None
        if isinstance(item, Comment) or isinstance(item, Submission):
            self.post = self.item
        self.view = InboxItemView(self.item)
        self.set_child(self.view)
        self.mark_read = self.view.mark_read


class InboxListbox(PostPreviewListbox):
    def __init__(self, post_gen_func, show_post_func, load_now=True, **kwargs):
        super().__init__(post_gen_func, show_post_func, load_now, **kwargs)

    def _on_post_preview_row_loaded(self, target):
        row = InboxListboxRow(target)
        self.append(row)
        row.show()

    def on_row_activate(self, lb, row):
        row.mark_read()
        super().on_row_activate(lb, row)


class InboxListView(Gtk.Box):
    def __init__(self, post_gen_func, show_post_func, load_now=True, **kwargs):
        super().__init__(orientation=Gtk.Orientation.VERTICAL, **kwargs)
        self.listbox = InboxListbox(post_gen_func, show_post_func, load_now)
        self.sw = SectionScrolledWindow(self.listbox)

        self.clamp = new_clamp()
        self.clamp.set_child(self.listbox)

        self.sw.set_child(self.clamp)
        self.headerbar = SinglePostStreamHeaderbar(_('Inbox'))
        self.headerbar.refresh_btn.connect(
            'clicked',
            lambda *args: self.listbox.refresh()
        )

        self.append(self.headerbar)

        self.append(self.sw)
