from gettext import ngettext
from gi.repository import Gio, GLib
from threading import Thread
from time import sleep


class NotifManager:
    def __init__(self, reddit, application, emit_func):
        self.reddit = reddit
        self.app = application
        self.old_len = -1
        self.__stop = False
        self.emit = emit_func

        self.thread = Thread(target=self.check_inbox, daemon=True)
        self.thread.start()

    def stop(self):
        self.__stop = True

    def __del__(self):
        self.__stop = True

    def check_inbox(self):
        while not self.__stop:
            inbox = list(self.reddit.inbox.unread(limit=None))
            len_inbox = len(inbox)
            if len_inbox != self.old_len:
                if len_inbox > 0:
                    title = ngettext(
                        '{0} new message', '{0} new messages', len_inbox
                    ).format(len_inbox)
                    body = '\n\n'.join([m.body for m in inbox[:3]])
                    if len_inbox > 3:
                        body += '\n\n' + ngettext(
                            '{0} more', '{0} more', len_inbox-3
                        ).format(
                            len_inbox-3
                        )
                    GLib.idle_add(self.send_notif, title, body)
                GLib.idle_add(self.emit, 'notif_count_change', str(len_inbox))
                self.old_len = len_inbox
            sleep(120)

    def send_notif(self, title, body):
        notif = Gio.Notification.new(title)
        notif.set_body(body)
        notif.set_default_action('app.goinbox')
        notif.set_icon(
            Gio.ThemedIcon.new(
                'org.gabmus.giara-symbolic'
            )
        )
        self.app.send_notification('new_inbox_items', notif)
