#!/usr/bin/python3
"""Display measured install progress in English and Hebrew, without more setup choices."""
import math
import threading
import time
from pathlib import Path

import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, GdkPixbuf, GLib, Gtk
from progress import Journal, Progress, STAGES, clock_text, media_estimate
from session_inhibit import hold_awake

STYLE = b"""
window { background-color: #102c40; color: #f5f9fa; }
.header { font: bold 22px Heebo, sans-serif; color: #f9db7d; }
.banner { border-radius: 8px; background-color: #183b4b; }
.stage { font: bold 25px Heebo, sans-serif; color: #fafbf8; }
.caption { font: 16px Heebo, sans-serif; color: #dbe6e7; }
.metric { font: bold 27px Heebo, sans-serif; color: #fff; }
progressbar trough { min-height: 12px; background-color: #335063; border: 0; border-radius: 6px; }
progressbar progress { min-height: 12px; background-color: #79d7b0; border: 0; border-radius: 6px; }
"""

def label(text="", style="caption", rtl=False):
    # Gtk flips start alignment when the widget has RTL direction.
    widget = Gtk.Label(label=text, xalign=0)
    widget.set_direction(Gtk.TextDirection.RTL if rtl else Gtk.TextDirection.LTR)
    widget.set_line_wrap(True)
    widget.get_style_context().add_class(style)
    return widget


class Display:
    def __init__(self, app=None):
        hold_awake()
        self.model = Progress(time.monotonic())
        self.journal = Journal()
        self.window = Gtk.ApplicationWindow(application=app, title="NewWorld") if app else Gtk.Window(title="NewWorld")
        self.window.set_position(Gtk.WindowPosition.CENTER)
        screen = self.window.get_screen()
        self.window.set_default_size(min(660, screen.get_width() - 12), min(410, screen.get_height() - 60))
        self.window.set_keep_above(True)
        # Closing a window must never interrupt a partially written disk.
        self.window.connect("delete-event", lambda *_: self.model.status == "running")
        if app is None:
            self.window.connect("destroy", Gtk.main_quit)
        css = Gtk.CssProvider()
        backdrop = Path("/usr/share/backgrounds/newworld/NewWorld.jpg")
        scene = ((".banner { background-image: linear-gradient(to right, rgba(9,33,49,.88), "
                  "rgba(9,33,49,.16)), url(\"" + backdrop.as_uri() + "\"); "
                  "background-size: cover; background-position: center; }").encode()
                 if backdrop.is_file() else b"")
        css.load_from_data(STYLE + scene)
        Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        panel = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=9)
        panel.set_border_width(22)
        scroll = Gtk.ScrolledWindow()
        scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scroll.add(panel)
        self.window.add(scroll)
        header = Gtk.Box(spacing=10)
        header.set_direction(Gtk.TextDirection.LTR)
        header.set_border_width(8)
        banner = Gtk.EventBox()
        banner.get_style_context().add_class("banner")
        banner.add(header)
        logo = Path("/usr/share/newworld/newworld-logo.png")
        if logo.is_file():
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(str(logo), 40, 40, True)
            header.pack_start(Gtk.Image.new_from_pixbuf(pixbuf), False, False, 0)
        header.pack_start(label("NewWorld", "header"), False, False, 0)
        panel.pack_start(banner, False, False, 0)
        self.en = label(style="stage")
        self.he = label(style="stage", rtl=True)
        panel.pack_start(self.en, False, False, 0)
        panel.pack_start(self.he, False, False, 0)
        self.bar = Gtk.ProgressBar()
        self.bar.set_direction(Gtk.TextDirection.LTR)
        panel.pack_start(self.bar, False, False, 6)
        self.percent = label(style="metric")
        self.eta = label(style="metric")
        for a, b, data in (("Overall progress", "התקדמות כוללת", self.percent),
                           ("Estimated time left", "זמן משוער לסיום", self.eta)):
            row = Gtk.Box(spacing=8)
            row.set_direction(Gtk.TextDirection.LTR)
            row.pack_start(label(a), True, True, 0)
            row.pack_start(data, False, False, 0)
            row.pack_end(label(b, rtl=True), True, True, 0)
            panel.pack_start(row, False, False, 0)
        self.hint = label()
        self.hint_he = label(rtl=True)
        panel.pack_start(self.hint, False, False, 3)
        panel.pack_start(self.hint_he, False, False, 0)
        self.painted_labels = {}
        self.painted_fraction = None
        self.tick()
        GLib.timeout_add(1000, self.tick)
        self.window.show_all()
        threading.Thread(target=self.measure, daemon=True).start()

    def measure(self):
        estimate = media_estimate()
        if estimate is not None:
            GLib.idle_add(self.set_estimate, estimate)

    def set_estimate(self, seconds):
        self.model.initial_seconds = seconds
        return False

    def tick(self):
        now = time.monotonic()
        for event in self.journal.read():
            ts = event.get("time", now)
            event_time = min(now, max(self.model.start, ts)) if isinstance(ts, (float,int)) and math.isfinite(ts) else now
            self.model.accept(event, event_time)
        _, _, english, hebrew = STAGES[self.model.stage]
        note = "Keep the installer USB connected."
        note_he = "יש להשאיר את כונן ההתקנה מחובר."
        if self.model.status == "success":
            english, hebrew = "Installation complete", "ההתקנה הושלמה"
            note = "Remove the installer USB before the computer starts again."
            note_he = "יש להוציא את כונן ההתקנה לפני הפעלת המחשב מחדש."
        if self.model.status == "error":
            english, hebrew = "Installation stopped", "ההתקנה נעצרה"
            note = self.model.detail or "The current step failed. Review the installer log before retrying."
            note_he = "השלב הנוכחי נכשל. יש לעיין ביומן ההתקנה לפני ניסיון נוסף."
        remaining = self.model.remaining(now)
        placeholder = "—" if self.model.status == "error" else "…"
        eta = clock_text(remaining) if remaining is not None else placeholder
        if remaining is None and self.model.status == "running":
            note, note_he = "Measuring installation speed…", "מתבצעת מדידת מהירות ההתקנה…"
        fraction = self.model.percent / 100
        if fraction != self.painted_fraction:
            self.bar.set_fraction(fraction)
            self.painted_fraction = fraction
        for widget, text in ((self.en, english), (self.he, hebrew),
                             (self.percent, f"{int(self.model.percent)}%"), (self.eta, eta),
                             (self.hint, note), (self.hint_he, note_he)):
            if self.painted_labels.get(widget) != text:
                widget.set_text(text)
                self.painted_labels[widget] = text
        return True


if __name__ == "__main__":
    display = Display()
    Gtk.main()
