from gettext import gettext as _
from gi.repository import Gtk, Pango
from praw.models import Comment, Submission, Message, Subreddit
from giara.custom_emoji import CustomEmoji
from enum import Enum
from typing import Optional, Union
import re


EMOJI_REGEX = re.compile(r':[a-zA-Z0-9_\-]+:')


class FlairTextColor(Enum):
    LIGHT = 'LIGHT'
    DARK = 'DARK'


class FlairLabel(Gtk.Box):
    styles = list()

    @classmethod
    def new_from_type(cls, item: Union[Comment, Submission, Message]):
        if isinstance(item, Comment):
            return cls(
                _('Comment'), '#3584e4', FlairTextColor.LIGHT
            )
        elif isinstance(item, Submission):
            return cls(
                _('Post'), '#3584e4', FlairTextColor.LIGHT
            )
        elif isinstance(item, Message):
            return cls(
                _('Message'), '#3584e4', FlairTextColor.LIGHT
            )
        else:
            raise TypeError(
                'Cannot create flair for unknown type '+type(item)
            )

    @classmethod
    def new_from_post(cls, post: Submission):
        return cls(
            post.link_flair_text,
            post.link_flair_background_color,
            FlairTextColor.LIGHT
            if post.link_flair_text_color.lower() == 'light'
            else FlairTextColor.DARK,
            subreddit=post.subreddit
        )

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

    @classmethod
    def new_type_video(cls):
        return cls(
            _('Video'), '#f6d32d', FlairTextColor.DARK
        )

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

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

    @classmethod
    def new_nsfw(cls):
        return cls(
            _('NSFW'), '#e01b24', FlairTextColor.LIGHT
        )

    def __init__(
            self, text: str, bg: str, fg: FlairTextColor,
            subreddit: Optional[Subreddit] = None
    ):
        super().__init__(hexpand=False, orientation=Gtk.Orientation.HORIZONTAL)

        if subreddit is not None:
            emoji_match = EMOJI_REGEX.search(text)
            while emoji_match is not None:
                emoji = text[emoji_match.start():emoji_match.end()]
                text = text.replace(emoji, '').strip()
                self.custom_emoji = CustomEmoji(subreddit, emoji)
                self.append(self.custom_emoji)
                emoji_match = EMOJI_REGEX.search(text)

        self.label = Gtk.Label(
            label=text, halign=Gtk.Align.START, wrap=True,
            wrap_mode=Pango.WrapMode.WORD_CHAR
        )
        self.append(self.label)
        style_context = self.get_style_context()
        style_context.add_class('flair')
        if fg and bg:
            flair_name = bg.replace('#', '0x')
            if flair_name not in FlairLabel.styles:
                FlairLabel.styles.append(flair_name)
                css = f'''.flair-bg-{flair_name} {{
                    background-color: {bg};
                }}'''
                css_provider = Gtk.CssProvider()
                css_provider.load_from_data(css.encode())
                Gtk.StyleContext().add_provider_for_display(
                    self.get_display(), css_provider,
                    Gtk.STYLE_PROVIDER_PRIORITY_USER
                )
            style_context.add_class(f'flair-bg-{flair_name}')
            style_context.add_class(f'''flair-fg-{
                "light" if fg == FlairTextColor.LIGHT else "dark"
            }''')
