from gettext import gettext as _
from gi.repository import Gtk, Pango
from praw.models import Comment, Submission, Message


class FlairLabel(Gtk.Label):
    @classmethod
    def new_from_type(cls, item):
        if isinstance(item, Comment):
            return cls(
                _('Comment'), '#3584e4', 'light'
            )
        elif isinstance(item, Submission):
            return cls(
                _('Post'), '#3584e4', 'light'
            )
        elif isinstance(item, Message):
            return cls(
                _('Message'), '#3584e4', 'light'
            )
        else:
            raise TypeError(
                'Cannot create flair for unknown type '+type(item)
            )

    @classmethod
    def new_from_post(cls, post):
        return cls(
            post.link_flair_text,
            post.link_flair_background_color,
            post.link_flair_text_color
        )

    @classmethod
    def new_type_image(cls):
        return cls(
            _('Image'), '#33d17a', 'dark'
        )

    @classmethod
    def new_type_video(cls):
        return cls(
            _('Video'), '#f6d32d', 'dark'
        )

    @classmethod
    def new_type_text(cls):
        return cls(
            _('Text'), '#986a44', 'light'
        )

    @classmethod
    def new_type_link(cls):
        return cls(
            _('Link'), '#3584e4', 'light'
        )

    def __init__(self, text, bg, fg, *args, **kwargs):
        super().__init__(text, *args, **kwargs)
        self.set_hexpand(False)
        self.set_halign(Gtk.Align.START)
        self.set_line_wrap(True)
        self.set_line_wrap_mode(Pango.WrapMode.WORD_CHAR)

        style_context = self.get_style_context()
        style_context.add_class('flair')
        if fg and bg:
            flair_name = (fg+bg).replace('#', '0x')
            css = f'''.flair-{flair_name} {{
                background-color: {bg};
                color: {"white" if fg == "light" else "black"};
            }}'''
            css_provider = Gtk.CssProvider()
            css_provider.load_from_data(css.encode())
            style_context.add_provider_for_screen(
                self.get_screen(), css_provider,
                Gtk.STYLE_PROVIDER_PRIORITY_USER
            )
            style_context.add_class(f'flair-{flair_name}')
