#!/usr/bin/python3
"""Justype's settings, taught words, problem report, and weekly statistics windows, for the input menu and IBus's
setup button.

The engine stays the only writer of the settings and the taught words: this calls its control object on the IBus bus,
named by IBUS_ADDRESS when the engine starts it. `justype-setup settings` or no argument shows the settings,
`justype-setup words` the taught words, `justype-setup report` the problem report, `justype-setup stats` the weekly
statistics, `justype-setup survey` the one-question survey.
"""

import http.client
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request

import gi

gi.require_version("IBus", "1.0")
from gi.repository import Gio, GLib, IBus  # noqa: E402

ENGINE = ("org.freedesktop.IBus.Justype", "/org/freedesktop/IBus/Justype/Control", "dev.whitekr.Justype1")
FEEDBACK_URL = os.environ.get("JUSTYPE_FEEDBACK_URL") or "https://justype.whitekr.dev/feedback"
SENT_INFO = "함께 보내는 정보: 버전, 모델, 운영체제, 입력 중이던 앱, 학습한 단어 수, 사용 기록 설정"
NOT_RUNNING = "Justype 입력기가 켜져 있지 않습니다. 입력 소스를 Justype으로 바꾼 뒤 다시 열어 주세요."
EXPORT_NAME = "justype-taught-words.tsv"
STATS_EXPLANATION = (
    "켜 두면 일주일에 한 번, 아래와 같은 숫자만 개발자에게 보냅니다. Justype가 얼마나 자주 틀리는지, "
    "모델을 바꿀 때마다 나아지는지 확인하는 데 씁니다.\n"
    "입력한 글자, 누른 키, 단어, 앱 이름은 보내지 않습니다. 사용 기록을 켜지 않아도 되고, "
    "서버는 받은 날짜만 남기고 주소나 기기를 알 수 있는 정보는 저장하지 않습니다."
)


SURVEY_QUESTION = "Justype가 한글과 영어를 잘 맞히나요?"
# Best first, as shell/src/survey.rs lists them. The value is what the relay receives.
SURVEY_ANSWERS = [("거의 항상 맞힘", 5), ("대체로 맞힘", 4), ("반반", 3), ("자주 틀림", 2), ("거의 못 맞힘", 1)]
SURVEY_SENT_INFO = "함께 보내는 정보: 버전, 모델, 운영체제. 입력한 단어와 앱은 보내지 않습니다."


LANGUAGES_CAPTION = "단어마다 켜 둔 언어 중 무엇인지 자동으로 맞힙니다. 하나만 켜 두면 단어 바꾸기 키는 아무것도 하지 않습니다."
# Name in the settings, and the row's title.
LANGUAGE_ROWS = [("ko", "한국어"), ("en", "영어"), ("ja", "일본어")]
NOT_READY = "준비 중"
NO_OFF_APPS = "꺼 둔 앱이 없습니다. 입력 메뉴의 ‘이 앱에서 끄기’로 끌 수 있습니다."


def taught_words_label(count):
    return "모델을 불러오지 못해 학습한 단어를 볼 수 없습니다." if count is None else f"학습한 단어 {count}개"


def stats_state(on):
    return "주간 통계를 보내는 중입니다." if on else "주간 통계를 보내지 않습니다."


def stats_caption(on):
    return "다음에 보낼 내용 (이번 주에 지금까지 센 숫자):" if on else "보낼 내용 (켜면 0부터 셉니다):"


def word_label(word):
    return f"{word['guess']} → {word['text']}" if word["text"] != word["guess"] else word["text"]


def first_flipped(words):
    return next((i for i, w in enumerate(words) if w["text"] != w["guess"]), None)


def report_payload(report, note, chosen, with_usage=True):
    """The engine's report with the writer's note, only the words they picked, and the usage counts if they kept them."""
    payload = {**report, "note": note, "words": [w for i, w in enumerate(report["words"]) if i in chosen]}
    if not with_usage:
        payload.pop("usage", None)
    return payload


def usage_label(usage):
    return f"사용 기록 요약도 보내기 (최근 {usage['days']}일, 단어 {usage['words']}개, 숫자만)"


def post(url, payload, timeout=20):
    """The HTTP status the site answered and what it said, or 0 and why when no answer came."""
    body = json.dumps(payload).encode()
    try:
        # Cloudflare answers 403 to urllib's default User-Agent.
        headers = {"Content-Type": "application/json", "User-Agent": "justype-setup"}
        request = urllib.request.Request(url, data=body, headers=headers, method="POST")
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, ""
    except urllib.error.HTTPError as refusal:
        with refusal:
            try:
                return refusal.code, refusal.read(4096).decode(errors="replace")
            except (OSError, http.client.HTTPException):
                return refusal.code, ""
    except (OSError, ValueError, http.client.HTTPException) as error:
        return 0, str(error)


def taken(status):
    return 200 <= status < 300


def failure_message(status):
    """What the report window says when a report did not go through, given the status from `post`."""
    if status == 0:
        return "보내지 못했습니다. 인터넷 연결을 확인하고 다시 시도해 주세요."
    if status == 429:
        return "신고가 너무 많아 서버가 받지 않았습니다. 한 시간쯤 뒤에 다시 시도해 주세요. (HTTP 429)"
    if status >= 500:
        return f"서버에 문제가 있어 보내지 못했습니다. 잠시 뒤에 다시 시도해 주세요. (HTTP {status})"
    return f"서버가 신고를 받지 않았습니다. 인터넷 연결 문제는 아닙니다. 앱을 업데이트한 뒤 다시 시도해 주세요. (HTTP {status})"


def log_failure(command, outcome, detail):
    """One line in errors.log, as the engine writes it in shell/src/shared.rs, since nothing shows this stderr."""
    tail = " ".join(detail.split())[-500:]
    line = f"{int(time.time())}\t{command}\t{outcome}\t{tail}\n"
    base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
    try:
        os.makedirs(os.path.join(base, "justype"), exist_ok=True)
        with open(os.path.join(base, "justype", "errors.log"), "a", encoding="utf-8") as log:
            log.write(line)
    except OSError as error:
        print(f"justype-setup: could not write errors.log: {error}; {line}", file=sys.stderr)


def send_report(url, payload):
    """Posts a report and leaves a line in errors.log unless the site took it. The line never holds the report."""
    status, detail = post(url, payload)
    if not taken(status):
        log_failure(f"report POST {url}", f"HTTP {status}" if status else "no answer", detail)
    return status


class Engine:
    def __init__(self):
        self.connection = IBus.Bus().get_connection()

    def call(self, method, signature=None, *args):
        if self.connection is None:
            raise GLib.Error(NOT_RUNNING)
        params = GLib.Variant(signature, args) if signature else None
        reply = self.connection.call_sync(*ENGINE, method, params, None, Gio.DBusCallFlags.NONE, 5000, None)
        values = reply.unpack()
        return values[0] if values else None

    def taught_words(self):
        return [{"keys": keys, "text": text} for keys, text in self.call("TaughtWords")]

    def forget(self, keys):
        self.call("ForgetTaughtWord", "(s)", keys)

    def forget_all(self):
        self.call("ForgetTaughtWords")

    def export_words(self):
        return self.call("ExportTaughtWords")

    def import_words(self, text):
        return self.call("ImportTaughtWords", "(s)", text)

    def report(self):
        return json.loads(self.call("Report"))

    def weekly_stats(self):
        """Whether the weekly statistics are on, and the JSON they send."""
        return self.connection_call("WeeklyStats")

    def set_weekly_stats(self, on):
        self.call("SetWeeklyStats", "(b)", on)

    def settings(self):
        return json.loads(self.call("Settings"))

    def set_flip_key(self, name):
        self.call("SetFlipKey", "(s)", name)

    def set_languages(self, names):
        self.call("SetLanguages", "(s)", ",".join(names))


    def set_app_off(self, app, off):
        self.call("SetAppOff", "(sb)", app, off)

    def run(self, command):
        """What a menu command does, by its key, such as check-update."""
        self.call("Run", "(s)", command)

    def survey(self, answer, note):
        """The answer to post, with the build the engine knows."""
        return json.loads(self.call("Survey", "(ys)", answer, note))

    def connection_call(self, method):
        if self.connection is None:
            raise GLib.Error(NOT_RUNNING)
        reply = self.connection.call_sync(*ENGINE, method, None, None, Gio.DBusCallFlags.NONE, 5000, None)
        return reply.unpack()


def run(argv):
    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    from gi.repository import Gdk, Gtk

    def small(label, text):
        label.set_markup(f"<small>{GLib.markup_escape_text(text)}</small>")
        label.get_style_context().add_class("dim-label")

    class TaughtWordsWindow(Gtk.Window):
        def __init__(self, app, engine):
            super().__init__(application=app, title="학습한 단어")
            self.engine = engine
            self.set_default_size(420, 360)
            self.set_keep_above(True)
            self.store = Gtk.ListStore(str, str)
            self.table = Gtk.TreeView(model=self.store)
            for i, title in enumerate(["단어", "입력한 키"]):
                column = Gtk.TreeViewColumn(title, Gtk.CellRendererText(), text=i)
                column.set_resizable(True)
                column.set_min_width(180)
                self.table.append_column(column)
            self.table.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
            self.table.get_selection().connect("changed", lambda s: self.forget_button.set_sensitive(s.count_selected_rows() > 0))
            self.table.connect("key-press-event", self.on_key)
            scroll = Gtk.ScrolledWindow()
            scroll.set_shadow_type(Gtk.ShadowType.IN)
            scroll.add(self.table)
            self.empty = Gtk.Label(label="아직 학습한 단어가 없습니다. 단어 바꾸기 키로 단어를 바꾸면 여기에 쌓입니다.")
            self.empty.set_line_wrap(True)
            self.empty.set_justify(Gtk.Justification.CENTER)
            self.empty.set_margin_start(24)
            self.empty.set_margin_end(24)
            self.empty.get_style_context().add_class("dim-label")
            self.stack = Gtk.Stack()
            self.stack.add_named(scroll, "words")
            self.stack.add_named(self.empty, "empty")
            self.forget_button = Gtk.Button(label="잊기")
            self.forget_button.connect("clicked", lambda _b: self.forget_selected())
            self.forget_all_button = Gtk.Button(label="모두 잊기…")
            self.forget_all_button.connect("clicked", lambda _b: self.forget_all())
            self.export_button = Gtk.Button(label="내보내기…")
            self.export_button.set_tooltip_text("다른 컴퓨터의 Justype에서 가져올 수 있는 파일로 저장합니다. macOS와 Linux 모두 됩니다.")
            self.export_button.connect("clicked", lambda _b: self.export_words())
            import_button = Gtk.Button(label="가져오기…")
            import_button.set_tooltip_text("다른 컴퓨터에서 내보낸 파일의 단어를 더합니다. 이미 학습한 단어는 그대로 둡니다.")
            import_button.connect("clicked", lambda _b: self.import_words())
            buttons = Gtk.Box(spacing=12)
            buttons.pack_start(self.forget_all_button, False, False, 0)
            buttons.pack_start(self.export_button, False, False, 0)
            buttons.pack_start(import_button, False, False, 0)
            buttons.pack_end(self.forget_button, False, False, 0)
            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, margin=12)
            box.pack_start(self.stack, True, True, 0)
            box.pack_start(buttons, False, False, 0)
            self.add(box)
            self.show_all()

        def reload(self):
            try:
                self.words = self.engine.taught_words()
            except GLib.Error:
                self.words = []
                self.empty.set_text(NOT_RUNNING)
            self.store.clear()
            for word in self.words:
                self.store.append([word["text"], word["keys"]])
            self.forget_button.set_sensitive(False)
            self.forget_all_button.set_sensitive(bool(self.words))
            self.export_button.set_sensitive(bool(self.words))
            self.stack.set_visible_child_name("words" if self.words else "empty")

        def on_key(self, _table, event):
            if event.keyval in (Gdk.KEY_Delete, Gdk.KEY_BackSpace, Gdk.KEY_KP_Delete):
                self.forget_selected()
                return True
            return False

        def forget_selected(self):
            _, paths = self.table.get_selection().get_selected_rows()
            if paths:
                for path in paths:
                    self.engine.forget(self.words[path.get_indices()[0]]["keys"])
                self.reload()

        def choose_file(self, action, title, button):
            dialog = Gtk.FileChooserDialog(title=title, transient_for=self, action=action, modal=True)
            dialog.add_button("취소", Gtk.ResponseType.CANCEL)
            dialog.add_button(button, Gtk.ResponseType.ACCEPT)
            dialog.set_default_response(Gtk.ResponseType.ACCEPT)
            if action == Gtk.FileChooserAction.SAVE:
                dialog.set_do_overwrite_confirmation(True)
                dialog.set_current_name(EXPORT_NAME)
            path = dialog.get_filename() if dialog.run() == Gtk.ResponseType.ACCEPT else None
            dialog.destroy()
            return path

        def tell(self, text, secondary=None, error=False):
            dialog = Gtk.MessageDialog(
                transient_for=self, modal=True, buttons=Gtk.ButtonsType.OK, text=text, secondary_text=secondary,
                message_type=Gtk.MessageType.ERROR if error else Gtk.MessageType.INFO,
            )
            dialog.run()
            dialog.destroy()

        def export_words(self):
            path = self.choose_file(Gtk.FileChooserAction.SAVE, "학습한 단어 내보내기", "저장")
            if path:
                try:
                    with open(path, "w", encoding="utf-8") as f:
                        f.write(self.engine.export_words())
                except (OSError, GLib.Error) as e:
                    self.tell("내보내지 못했습니다", str(e), error=True)

        def import_words(self):
            path = self.choose_file(Gtk.FileChooserAction.OPEN, "학습한 단어 가져오기", "가져오기")
            if not path:
                return
            try:
                with open(path, encoding="utf-8") as f:
                    taken = self.engine.import_words(f.read())
            except (OSError, UnicodeDecodeError, GLib.Error) as e:
                self.tell("가져오지 못했습니다", str(e), error=True)
                return
            if taken:
                self.tell(f"단어 {taken}개를 가져왔습니다.")
            else:
                self.tell("가져올 단어가 없습니다", "Justype에서 내보낸 파일인지 확인해 주세요.", error=True)
            self.reload()

        def forget_all(self):
            dialog = Gtk.MessageDialog(
                transient_for=self, modal=True, message_type=Gtk.MessageType.WARNING,
                text=f"학습한 단어 {len(self.words)}개를 모두 잊을까요?",
                secondary_text="단어 바꾸기 키로 가르친 단어를 모두 지웁니다. 되돌릴 수 없습니다.",
            )
            dialog.add_button("모두 잊기", Gtk.ResponseType.ACCEPT).get_style_context().add_class("destructive-action")
            dialog.add_button("취소", Gtk.ResponseType.CANCEL)
            dialog.set_default_response(Gtk.ResponseType.CANCEL)
            if dialog.run() == Gtk.ResponseType.ACCEPT:
                self.engine.forget_all()
            dialog.destroy()
            self.reload()

    WIDTH = 400

    class ReportWindow(Gtk.Window):
        def __init__(self, app, report):
            super().__init__(application=app, title="문제 신고")
            self.report = report
            self.set_default_size(WIDTH, -1)
            self.set_resizable(False)
            self.set_keep_above(True)
            self.words_label = Gtk.Label(xalign=0)
            self.word_buttons = []
            self.word_rows = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
            if report["words"]:
                small(self.words_label, "문제가 된 단어를 누르면 그 단어만 함께 보냅니다")
                self.word_buttons = [Gtk.ToggleButton(label=word_label(w), can_focus=False, tooltip_text=w.get("app") or None)
                                     for w in report["words"]]
                flipped = first_flipped(report["words"])
                if flipped is not None:
                    self.word_buttons[flipped].set_active(True)
            else:
                small(self.words_label, "보낼 최근 입력이 없습니다")
            self.note = Gtk.Entry(placeholder_text="한 줄 메모 (선택)", activates_default=True)
            self.usage = Gtk.CheckButton(label=usage_label(report["usage"]), active=True, can_focus=False) \
                if "usage" in report else None
            self.sent_label = Gtk.Label(xalign=0, wrap=True)
            small(self.sent_label, SENT_INFO)
            self.status = Gtk.Label(xalign=0, wrap=True)
            cancel = Gtk.Button(label="취소")
            cancel.connect("clicked", lambda _b: self.destroy())
            self.send_button = Gtk.Button(label="보내기", can_default=True)
            self.send_button.get_style_context().add_class("suggested-action")
            self.send_button.connect("clicked", lambda _b: self.send())
            self.buttons = Gtk.Box(spacing=8)
            self.buttons.pack_end(self.send_button, False, False, 0)
            self.buttons.pack_end(cancel, False, False, 0)
            self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10, margin=16)
            rows = [self.words_label, self.word_rows, self.note, self.usage, self.sent_label, self.status, self.buttons]
            for row in [r for r in rows if r is not None]:
                self.box.pack_start(row, False, False, 0)
            self.add(self.box)
            self.connect("key-press-event", self.on_key)
            self.show_all()
            self.lay_out_word_rows()
            self.word_rows.set_visible(bool(report["words"]))
            self.status.hide()
            self.send_button.grab_default()
            self.note.grab_focus()

        def lay_out_word_rows(self):
            """Packs the words into rows by width, as the macOS window does; a FlowBox would line them up in
            columns. Buttons know their width only once they are in a window."""
            measure = Gtk.Box()
            self.word_rows.pack_start(measure, False, False, 0)
            for button in self.word_buttons:
                measure.pack_start(button, False, False, 0)
            measure.show_all()
            widths = [b.get_preferred_width()[1] for b in self.word_buttons]
            self.word_rows.remove(measure)
            row, used = None, 0
            for button, width in zip(self.word_buttons, widths):
                measure.remove(button)
                if row is None or used + 6 + width > WIDTH - 32:
                    row, used = Gtk.Box(spacing=6), -6
                    self.word_rows.pack_start(row, False, False, 0)
                row.pack_start(button, False, False, 0)
                used += 6 + width
            self.word_rows.show_all()

        def on_key(self, _window, event):
            if event.keyval != Gdk.KEY_Escape:
                return False
            self.destroy()
            return True

        def send(self):
            chosen = {i for i, b in enumerate(self.word_buttons) if b.get_active()}
            payload = report_payload(self.report, self.note.get_text(), chosen,
                                     self.usage is not None and self.usage.get_active())
            self.send_button.set_sensitive(False)
            self.show_status("보내는 중…")

            def work():
                GLib.idle_add(self.sent, send_report(FEEDBACK_URL, payload))

            threading.Thread(target=work, daemon=True).start()

        def sent(self, status):
            if taken(status):
                for view in [self.words_label, self.word_rows, self.note, self.usage, self.sent_label, self.buttons]:
                    if view is not None:
                        view.hide()
                self.show_status("신고했습니다. 고맙습니다.")
                GLib.timeout_add(1500, self.destroy)
            else:
                self.send_button.set_sensitive(True)
                self.show_status(failure_message(status), "#c01c28")
            self.resize(1, 1)
            return False

        def show_status(self, text, color=None):
            escaped = GLib.markup_escape_text(text)
            self.status.set_markup(f'<span foreground="{color}">{escaped}</span>' if color else escaped)
            self.status.show()

    class StatsWindow(Gtk.Window):
        """Explains the weekly statistics and shows the JSON they send, before the writer turns them on and later."""

        def __init__(self, app, engine):
            super().__init__(application=app, title="주간 통계")
            self.engine = engine
            self.set_default_size(440, -1)
            self.set_resizable(False)
            self.set_keep_above(True)
            explanation = Gtk.Label(label=STATS_EXPLANATION, xalign=0, wrap=True, max_width_chars=50)
            self.caption = Gtk.Label(xalign=0)
            self.json = Gtk.TextView(editable=False, cursor_visible=False, monospace=True,
                                     left_margin=6, right_margin=6, top_margin=6, bottom_margin=6)
            scroll = Gtk.ScrolledWindow(min_content_height=230, shadow_type=Gtk.ShadowType.IN)
            scroll.add(self.json)
            self.close_button = Gtk.Button()
            self.close_button.connect("clicked", lambda _b: self.destroy())
            self.toggle_button = Gtk.Button(can_default=True)
            self.toggle_button.connect("clicked", lambda _b: self.toggle())
            buttons = Gtk.Box(spacing=8)
            buttons.pack_end(self.toggle_button, False, False, 0)
            buttons.pack_end(self.close_button, False, False, 0)
            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10, margin=16)
            for row in [explanation, self.caption, scroll, buttons]:
                box.pack_start(row, False, False, 0)
            self.add(box)
            self.connect("key-press-event", self.on_key)
            self.reload()
            self.show_all()
            self.toggle_button.grab_default()

        def reload(self):
            on, payload = self.engine.weekly_stats()
            small(self.caption, stats_caption(on))
            self.json.get_buffer().set_text(payload)
            self.toggle_button.set_label("끄기" if on else "켜기")
            self.close_button.set_label("닫기" if on else "취소")
            self.on = on

        def toggle(self):
            try:
                self.engine.set_weekly_stats(not self.on)
            except GLib.Error:
                app = self.get_application()
                self.destroy()
                app.message(NOT_RUNNING)
                return
            self.reload()

        def on_key(self, _window, event):
            if event.keyval != Gdk.KEY_Escape:
                return False
            self.destroy()
            return True

    class SurveyWindow(Gtk.Window):
        """The one question, its five answers, a note, and sending. Opening it already ended the survey."""

        def __init__(self, app, engine):
            super().__init__(application=app, title="짧은 설문")
            self.engine = engine
            self.set_default_size(WIDTH, -1)
            self.set_resizable(False)
            self.set_keep_above(True)
            question = Gtk.Label(xalign=0, wrap=True)
            question.set_markup(f"<b>{GLib.markup_escape_text(SURVEY_QUESTION)}</b>")
            self.choices = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
            self.answers = []
            group = None
            for title, value in SURVEY_ANSWERS:
                button = Gtk.RadioButton.new_with_label_from_widget(group, title)
                group = group or button
                self.answers.append((button, value))
                self.choices.pack_start(button, False, False, 0)
            # A radio group always has one on; this hidden one stands for no answer yet.
            self.none = Gtk.RadioButton.new_from_widget(group)
            self.none.set_active(True)
            self.note = Gtk.Entry(placeholder_text="더 하고 싶은 말 (선택)", activates_default=True)
            self.sent_label = Gtk.Label(xalign=0, wrap=True)
            small(self.sent_label, SURVEY_SENT_INFO)
            self.status = Gtk.Label(xalign=0, wrap=True)
            close = Gtk.Button(label="닫기")
            close.connect("clicked", lambda _b: self.destroy())
            self.send_button = Gtk.Button(label="보내기", can_default=True, sensitive=False)
            self.send_button.get_style_context().add_class("suggested-action")
            self.send_button.connect("clicked", lambda _b: self.send())
            for button, _value in self.answers:
                button.connect("toggled", lambda _b: self.send_button.set_sensitive(self.picked() is not None))
            self.buttons = Gtk.Box(spacing=8)
            self.buttons.pack_end(self.send_button, False, False, 0)
            self.buttons.pack_end(close, False, False, 0)
            self.form = [question, self.choices, self.note, self.sent_label, self.buttons]
            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10, margin=16)
            for row in self.form[:-1] + [self.status, self.buttons]:
                box.pack_start(row, False, False, 0)
            self.add(box)
            self.connect("key-press-event", self.on_key)
            self.show_all()
            self.status.hide()
            self.send_button.grab_default()

        def picked(self):
            return next((value for button, value in self.answers if button.get_active()), None)

        def send(self):
            answer = self.picked()
            if answer is None:
                return
            try:
                payload = self.engine.survey(answer, self.note.get_text())
            except GLib.Error:
                app = self.get_application()
                self.destroy()
                app.message(NOT_RUNNING)
                return
            self.send_button.set_sensitive(False)
            self.show_status("보내는 중…")

            def work():
                GLib.idle_add(self.sent, send_report(FEEDBACK_URL, payload))

            threading.Thread(target=work, daemon=True).start()

        def sent(self, status):
            if taken(status):
                for view in self.form:
                    view.hide()
                self.show_status("보냈습니다. 고맙습니다.")
                GLib.timeout_add(1500, self.destroy)
            else:
                self.send_button.set_sensitive(True)
                self.show_status(failure_message(status), "#c01c28")
            self.resize(1, 1)
            return False

        def show_status(self, text, color=None):
            escaped = GLib.markup_escape_text(text)
            self.status.set_markup(f'<span foreground="{color}">{escaped}</span>' if color else escaped)
            self.status.show()

        def on_key(self, _window, event):
            if event.keyval != Gdk.KEY_Escape:
                return False
            self.destroy()
            return True

    class SettingsWindow(Gtk.Window):
        """What the input menu does not hold, in five pages. Each change goes to the engine at once."""

        PAGES = [("general", "일반"), ("language", "언어"), ("words", "학습한 단어"), ("privacy", "개인정보"), ("about", "정보")]

        def __init__(self, app, engine):
            super().__init__(application=app, title="Justype 설정")
            self.engine = engine
            self.loading = False
            self.set_default_size(640, 420)
            self.stack = Gtk.Stack()
            sidebar = Gtk.StackSidebar(stack=self.stack)
            sidebar.set_size_request(150, -1)
            pages = {"general": self.general_page(), "language": self.language_page(), "words": self.words_page(),
                     "privacy": self.privacy_page(), "about": self.about_page()}
            for name, title in self.PAGES:
                self.stack.add_titled(pages[name], name, title)
            box = Gtk.Box()
            box.pack_start(sidebar, False, False, 0)
            box.pack_start(Gtk.Separator(orientation=Gtk.Orientation.VERTICAL), False, False, 0)
            box.pack_start(self.stack, True, True, 0)
            self.add(box)
            self.connect("key-press-event", self.on_key)
            self.reload()
            self.show_all()
            # An update check or install the 정보 page started finishes later, so the page follows it.
            self.timer = GLib.timeout_add_seconds(2, self.poll)
            self.connect("destroy", lambda _w: GLib.source_remove(self.timer))

        @staticmethod
        def page():
            return Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8, margin=20)

        @staticmethod
        def heading(text):
            label = Gtk.Label(xalign=0)
            label.set_markup(f"<b>{GLib.markup_escape_text(text)}</b>")
            return label

        def general_page(self):
            box = self.page()
            box.pack_start(self.heading("단어 바꾸기 키"), False, False, 0)
            self.flip_key = Gtk.ComboBoxText()
            self.flip_key.connect("changed", lambda c: self.change(lambda: self.engine.set_flip_key(c.get_active_id())))
            flip_caption = Gtk.Label(xalign=0, wrap=True)
            small(flip_caption, "방금 친 단어를 한글과 영어 사이에서 바꿉니다.")
            box.pack_start(self.flip_key, False, False, 0)
            box.pack_start(flip_caption, False, False, 0)
            off = self.heading("꺼 둔 앱")
            off.set_margin_top(16)
            box.pack_start(off, False, False, 0)
            self.off_apps = Gtk.ListBox(selection_mode=Gtk.SelectionMode.NONE)
            self.off_apps.set_placeholder(self.dim(NO_OFF_APPS))
            frame = Gtk.Frame()
            frame.add(self.off_apps)
            box.pack_start(frame, False, False, 0)
            return box

        def language_page(self):
            box = self.page()
            box.pack_start(self.heading("입력 언어"), False, False, 0)
            self.language_boxes = {}
            for name, title in LANGUAGE_ROWS:
                check = Gtk.CheckButton(label=title)
                check.connect("toggled", lambda _c: self.change(lambda: self.engine.set_languages(self.picked_languages())))
                self.language_boxes[name] = check
                box.pack_start(check, False, False, 0)
            caption = Gtk.Label(xalign=0, wrap=True)
            small(caption, LANGUAGES_CAPTION)
            box.pack_start(caption, False, False, 0)
            return box

        def picked_languages(self):
            return [name for name, _ in LANGUAGE_ROWS if self.language_boxes[name].get_active()]

        def show_languages(self, view, loaded):
            picked = view.get("languages", ["ko", "en"])
            for name, title in LANGUAGE_ROWS:
                check = self.language_boxes[name]
                ready = name != "ja" or view.get("japanese", False)
                check.set_label(title if ready else f"{title} ({NOT_READY})")
                check.set_active(name in picked)
                # The last language left on stays on, since words need one to be read in.
                check.set_sensitive(loaded and ready and not (picked == [name]))

        def words_page(self):
            box = self.page()
            self.words_label = Gtk.Label(xalign=0, wrap=True)
            caption = Gtk.Label(xalign=0, wrap=True)
            small(caption, "단어 바꾸기 키로 바꾼 단어는 다음부터 그대로 입력됩니다. 목록에서 잊게 하거나 다른 컴퓨터로 옮길 수 있습니다.")
            self.words_button = Gtk.Button(label="학습한 단어 관리…", halign=Gtk.Align.START)
            self.words_button.connect("clicked", lambda _b: self.get_application().show_words())
            for row in [self.words_label, caption, self.words_button]:
                box.pack_start(row, False, False, 0)
            return box

        def privacy_page(self):
            box = self.page()
            self.stats_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
            self.stats_label = Gtk.Label(xalign=0, wrap=True)
            stats_button = Gtk.Button(label="주간 통계 보내기…", halign=Gtk.Align.START)
            stats_button.connect("clicked", lambda _b: self.get_application().show_stats())
            stats_caption_label = Gtk.Label(xalign=0, wrap=True)
            small(stats_caption_label, "켜기 전에 보내는 내용을 그대로 보여 줍니다. 입력한 글자, 단어, 앱 이름은 보내지 않습니다.")
            self.stats_box.pack_start(self.heading("주간 통계"), False, False, 0)
            for row in [self.stats_label, stats_caption_label, stats_button]:
                self.stats_box.pack_start(row, False, False, 0)
            box.pack_start(self.stats_box, False, False, 0)
            return box

        def about_page(self):
            box = self.page()
            name = Gtk.Label(xalign=0)
            name.set_markup("<big><b>Justype</b></big>")
            self.status = Gtk.Label(xalign=0, wrap=True)
            self.update_buttons = Gtk.Box(spacing=8)
            practice = Gtk.Button(label="사용법 연습…")
            practice.connect("clicked", lambda _b: self.change(lambda: self.engine.run("practice")))
            report = Gtk.Button(label="문제 신고 및 개선 제안…")
            # Through the engine, as the menu item does, so the report holds the words typed up to now.
            report.connect("clicked", lambda _b: self.change(lambda: self.engine.run("report")))
            more = Gtk.Box(spacing=8, margin_top=16)
            more.pack_start(practice, False, False, 0)
            more.pack_start(report, False, False, 0)
            for row in [name, self.status, self.update_buttons, more]:
                box.pack_start(row, False, False, 0)
            return box

        @staticmethod
        def dim(text):
            label = Gtk.Label(label=text, wrap=True, margin=12)
            label.get_style_context().add_class("dim-label")
            return label

        def change(self, call):
            """Sends a change the writer made, not one `reload` made, and shows what the engine then holds."""
            if self.loading:
                return
            try:
                call()
            except GLib.Error:
                app = self.get_application()
                self.destroy()
                app.message(NOT_RUNNING)
                return
            self.reload()

        def reload(self):
            try:
                view = self.engine.settings()
            except GLib.Error:
                app = self.get_application()
                GLib.idle_add(self.destroy)
                app.message(NOT_RUNNING)
                return
            self.loading = True
            try:
                self.show_view(view)
            finally:
                self.loading = False

        def show_view(self, view):
            loaded = view["taught_words"] is not None
            if self.flip_key.get_model() is None or len(self.flip_key.get_model()) == 0:
                for key in view["flip_keys"]:
                    self.flip_key.append(key["name"], key["title"])
            self.flip_key.set_active_id(view["flip_key"])
            self.flip_key.set_sensitive(loaded)
            self.show_languages(view, loaded)
            for row in self.off_apps.get_children():
                self.off_apps.remove(row)
            for app in view["off_apps"]:
                row = Gtk.Box(spacing=8, margin=6)
                # 3 is Pango.EllipsizeMode.END.
                row.pack_start(Gtk.Label(label=app, xalign=0, ellipsize=3), True, True, 0)
                button = Gtk.Button(label="다시 켜기")
                button.connect("clicked", lambda _b, app=app: self.change(lambda: self.engine.set_app_off(app, False)))
                row.pack_end(button, False, False, 0)
                self.off_apps.add(row)
            self.off_apps.show_all()
            self.words_label.set_text(taught_words_label(view["taught_words"]))
            self.words_button.set_sensitive(loaded)
            self.stats_box.set_visible(view["weekly_stats"] is not None)
            self.stats_box.set_no_show_all(view["weekly_stats"] is None)
            if view["weekly_stats"] is not None:
                self.stats_label.set_text(stats_state(view["weekly_stats"]))
            self.show_update(view)

        def show_update(self, view):
            self.status.set_text(view["status"])
            for button in self.update_buttons.get_children():
                self.update_buttons.remove(button)
            for item in view["update"]:
                button = Gtk.Button(label=item["title"], sensitive=item["enabled"])
                button.connect("clicked", lambda _b, command=item["command"]: self.change(lambda: self.engine.run(command)))
                self.update_buttons.pack_start(button, False, False, 0)
            self.update_buttons.show_all()

        def poll(self):
            try:
                view = self.engine.settings()
            except GLib.Error:
                return True
            if self.status.get_text() != view["status"] or len(self.update_buttons.get_children()) != len(view["update"]):
                self.show_update(view)
            return True

        def on_key(self, _window, event):
            if event.keyval != Gdk.KEY_Escape:
                return False
            self.destroy()
            return True

    class Setup(Gtk.Application):
        def __init__(self):
            super().__init__(application_id="dev.whitekr.Justype.Setup", flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
            self.engine = None
            self.words = None
            self.report = None
            self.stats = None
            self.survey = None
            self.settings = None

        def do_command_line(self, command_line):
            if self.engine is None:
                self.engine = Engine()
            args = command_line.get_arguments()[1:]
            command = args[0] if args else "settings"
            show = {"survey": self.show_survey, "stats": self.show_stats, "report": self.show_report,
                    "words": self.show_words}.get(command, self.show_settings)
            return show()

        def show_settings(self):
            if self.settings is None:
                try:
                    self.engine.settings()
                except GLib.Error:
                    self.message(NOT_RUNNING)
                    return 1
                self.settings = SettingsWindow(self, self.engine)
                self.settings.connect("destroy", lambda _w: setattr(self, "settings", None))
            else:
                self.settings.reload()
            self.settings.present()
            return 0

        def show_survey(self):
            if self.survey is None:
                self.survey = SurveyWindow(self, self.engine)
                self.survey.connect("destroy", lambda _w: setattr(self, "survey", None))
            self.survey.present()
            return 0

        def show_stats(self):
            if self.stats is not None:
                self.stats.destroy()
            try:
                self.engine.weekly_stats()
            except GLib.Error:
                self.message(NOT_RUNNING)
                return 1
            self.stats = StatsWindow(self, self.engine)
            self.stats.connect("destroy", lambda _w: self.closed_stats())
            self.stats.present()
            return 0

        def closed_stats(self):
            self.stats = None
            if self.settings is not None:
                self.settings.reload()

        def show_report(self):
            if self.report is not None:
                self.report.destroy()
            try:
                report = self.engine.report()
            except GLib.Error:
                self.message(NOT_RUNNING)
                return 1
            self.report = ReportWindow(self, report)
            self.report.connect("destroy", lambda _w: setattr(self, "report", None))
            self.report.present()
            return 0

        def show_words(self):
            if self.words is None:
                self.words = TaughtWordsWindow(self, self.engine)
                self.words.connect("destroy", lambda _w: self.closed_words())
            self.words.reload()
            self.words.present()
            return 0

        def closed_words(self):
            self.words = None
            if self.settings is not None:
                self.settings.reload()

        def message(self, text):
            dialog = Gtk.MessageDialog(message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.CLOSE, text=text)
            dialog.run()
            dialog.destroy()

    return Setup().run(argv)


if __name__ == "__main__":
    sys.exit(run(sys.argv))
