#!/usr/bin/python3
import gettext
import gi
import locale
import os
import subprocess
import sys
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

# i18n
gettext.install("mintchat", "/usr/share/locale")
from locale import gettext as _
locale.bindtextdomain("mintchat", "/usr/share/locale")
locale.textdomain("mintchat")

NORUN_FLAG = os.path.expanduser("~/.linuxmint/mintchat/norun.flag")

class MintChat():

    def __init__(self):
        builder = Gtk.Builder()
        builder.set_translation_domain("mintchat")
        builder.add_from_file('/usr/share/linuxmint/mintchat/mintchat.ui')

        window = builder.get_object("main_window")
        window.set_icon_name("mintchat")
        window.set_position(Gtk.WindowPosition.CENTER)
        window.connect("destroy", Gtk.main_quit)

        # Action buttons
        builder.get_object("connect_button").connect("clicked", self.connect)

        # Construct the bottom toolbar
        checkbox = builder.get_object("norun_checkbox")
        checkbox.set_active(os.path.exists(NORUN_FLAG))
        checkbox.connect("toggled", self.on_checkbox_toggled)

        text_buffer = builder.get_object("textbuffer1")
        end_iter = text_buffer.get_end_iter()
        text_buffer.insert(end_iter, _("Be nice and respectful with other users."))
        text_buffer.insert(end_iter, "\n")
        text_buffer.insert(end_iter, _("Be patient, it might take time before you get an answer."))
        text_buffer.insert(end_iter, "\n")
        text_buffer.insert(end_iter, _("Chat in English if possible. You will be more likely to get help than in other languages."))
        text_buffer.insert(end_iter, "\n")
        text_buffer.insert(end_iter, _("If you need to paste a lot of text, don't flood the channel, use pastebin.com."))
        text_buffer.insert(end_iter, "\n")
        text_buffer.insert(end_iter, _("Don't talk about politics, religion, ideology."))
        text_buffer.insert(end_iter, "\n")
        text_buffer.insert(end_iter, _("Don't talk about adult topics or anything that is not kids-friendly."))
        text_buffer.insert(end_iter, "\n")
        text_buffer.insert(end_iter, _("DON'T SHOUT (by typing in capital letters)."))

        window.show_all()

    def on_checkbox_toggled(self, button):
        if button.get_active():
            os.system("mkdir -p ~/.linuxmint/mintchat")
            os.system("touch %s" % NORUN_FLAG)
        else:
            if os.path.exists(NORUN_FLAG):
                os.system("rm -f %s" % NORUN_FLAG)

    def connect(self, button):
        subprocess.Popen(["mintchat-launch"])
        sys.exit(0)

if __name__ == "__main__":
    if os.path.exists(NORUN_FLAG):
        print(f"{NORUN_FLAG} found, launching Element.")
        subprocess.Popen(["mintchat-launch"])
    else:
        MintChat()
        Gtk.main()
