"""Screenshot jobs for src/bnchelp.html, named after the figure numbers.

Live jobs (docstring 'live') connect to igs-ip.net / products.igs-ip.net; with
--user the account replaces 'Example:Configs' of the example configurations.
Nothing is uploaded: upload panels are only shown, not started.

Click positions are client coordinates of the main window (1200x850, Fusion
style); they have to be adapted if the layout of a panel changes.
"""

import os
import subprocess
import time
import urllib.request

from shoot import (BNC, BNC_ROOT, BNCENV, Bnc, activate, click, crop_file, frame, key,
                   new_window, place, saved, shot, typetext, visible_windows, wait_window,
                   wshot, xdo)
import shoot

W, H = 1200, 850       # main window client size
X0, Y0 = 40, 60        # main window position

START = (266, 835)        # 'Start' in the bottom bar
ADDSTREAM = (47, 835)     # 'Add Stream'
EDITOPTIONS = (779, 121)  # 'Set Edit Options' on 'RINEX Editing & QC'
CUSTOMTRAFO = (1132, 361) # 'Custom Trafo' on 'Upload Corrections'
PPP1_TAB = (1123, 47)     # 'PPP (1)' tab with startTab 11 (tab bar scrolled)
OPEN_MAP = (207, 152)     # 'Open Map' on 'PPP (4)'
LATENCY_TAB = (196, 618)  # 'Latency' tab of the log canvas
ADD_CASTER = (51, 77)     # buttons of the 'Add Stream' dialog
ADD_SERIAL = (310, 77)
LOG_CANVAS = "1182x212+10+620"   # log canvas in a main window screenshot

NO_UPLOAD = ("uploadMountpointsOut", ",,,2,,,IGS20,IGS-SSR,2,,,,,,,0 byte(s),")

# Throughput/latency (34, 35): observation streams of igs-ip.net; an account
# may be limited to about 20 simultaneous connections
MANY = ["ABMF00GLP0", "AC2300USA0", "AC2400USA0", "ACSO00USA0", "AIRA00JPN0", "ALAC00ESP0",
        "ALBH00CAN0", "ALIC00AUS0", "AREG00PER0", "ASCG00SHN0", "AUCK00NZL0", "BAKE00CAN0",
        "BAUT00DEU0", "BIK000KGZ0", "BILL00USA0", "BLYT00USA0", "BOAV00BRA0", "BRAZ00BRA0",
        "BRMG00DEU0", "BRST00FRA0"]


def main_window(job, conf, tab, logtab=0, keys=(), live=False):
    b = Bnc(job, conf, [("startTab", tab), ("statusTab", logtab)] + list(keys), live=live)
    place(b.main, X0, Y0, W, H)
    return b


def run_and_wait(b, seconds):
    click(b.main, *START)
    time.sleep(seconds)


def panel(job, name, conf, tab, logtab=0, keys=(), live=False, run=0):
    """main window showing a panel, optionally running for some seconds"""
    b = main_window(job, conf, tab, logtab, keys, live)
    if run:
        run_and_wait(b, run)
    shot(name, frame())
    b.stop()


# --- main window panels ---------------------------------------------------

def fig05():
    """Sections of the main window, labelled"""
    b = main_window("fig05", "22_Empty.bnc", 0)
    path = shot("Figure05", frame())
    b.stop()
    labels = [("Top menu bar", 58), ("Settings canvas", 240), ("Streams canvas", 530),
              ("Log canvas", 740), ("Bottom menu bar", 852)]
    blue, x = "#00a0e3", 1010
    subprocess.run(["convert", path, "-stroke", blue, "-strokewidth", "4", "-draw",
                    "line %d,%d %d,%d" % (x, labels[0][1], x, labels[-1][1]), path], check=True)
    for text, y in labels:
        lab = path + ".label.png"
        subprocess.run(["convert", "-background", blue, "-fill", "white", "-font", "DejaVu-Sans",
                        "-pointsize", "19", "-size", "200x34", "-gravity", "center",
                        "label:" + text, lab], check=True)
        subprocess.run(["composite", "-geometry", "+%d+%d" % (x - 100, y - 17), lab, path, path],
                       check=True)
        os.remove(lab)


def fig07():
    """Network panel with 'Ignore SSL authorization errors' (upper part)"""
    b = main_window("fig07", "22_Empty.bnc", 0, keys=[("sslIgnoreErrors", 2)])
    x, y, w, h = frame()
    shot("Figure07", (x, y, 760, 330))
    b.stop()


def fig08():
    """RINEX Observations panel (01_RinexObs)"""
    panel("fig08", "Figure08", "01_RinexObs.bnc", 2)


def fig09():
    """live: RINEX Ephemeris panel, BCEP00BKG0 running"""
    panel("fig09", "Figure09", "02_RinexEph.bnc", 3, live=True, run=90)


def fig10():
    """RINEX Editing & QC panel, Analyze (05_RinexQC)"""
    panel("fig10", "Figure10", "05_RinexQC.bnc", 4)


def fig16():
    """SP3 Comparison panel (upper part)"""
    b = main_window("fig16", "21_CompareSp3.bnc", 5)
    x, y, w, h = frame()
    shot("Figure16", (x, y, 760, 310))
    b.stop()


def fig18():
    """live: Broadcast Corrections panel, SSRA00BKG1 running"""
    panel("fig18", "Figure18", "03_BrdcCorr.bnc", 6, keys=[("corrPort", "5656")], live=True,
          run=60)


def fig19():
    """live: Feed Engine panel, running"""
    panel("fig19", "Figure19", "07_FeedEngine.bnc", 7, live=True, run=60)


def fig21():
    """live: Serial Output panel, running"""
    panel("fig21", "Figure21", "06_RTK.bnc", 8, live=True, run=60, keys=[
        ("mountPoints", "//Example:Configs@igs-ip.net:2101/FFMJ00DEU0 RTCM_3.3 DEU 50.09 8.66 no 2"),
        ("serialMountPoint", "FFMJ00DEU0")])


def fig22():
    """live: Miscellaneous panel, RTCM scan of CUT000AUS0"""
    panel("fig22", "Figure22", "22_Empty.bnc", 10, live=True, run=45, keys=[
        ("mountPoints", "//Example:Configs@igs-ip.net:2101/CUT000AUS0 RTCM_3.3 AUS -32.00 115.89 no 2"),
        ("miscMount", "CUT000AUS0"), ("miscIntr", "2 sec"), ("miscScanRTCM", "2"),
        ("miscPort", "4711")])


def fig23_26():
    """live: real-time PPP (08_PPP), panels 1-3 (23-25), panel 4 with track
    map (26), PPP plot (36); 20 min for a converged solution"""
    b = main_window("fig23_26", "08_PPP.bnc", 11, 3, live=True)
    run_and_wait(b, 1200)
    p = shot("Figure23", frame())
    crop_file(p, "Figure36", LOG_CANVAS)
    click(b.main, *PPP1_TAB)       # focus on the tab bar, then arrow keys
    key(b.main, "Right")
    time.sleep(1)
    shot("Figure24", frame())
    key(b.main, "Right")
    time.sleep(1)
    shot("Figure25", frame())
    key(b.main, "Right")
    time.sleep(1)
    click(b.main, *OPEN_MAP)
    m = wait_window("BNC: Map View", timeout=60)
    place(m, X0 + 270, Y0 + 110, 900, 640)
    time.sleep(40)                 # map tiles and some positions
    shot("Figure26", frame())
    b.stop()


def fig27():
    """PPP post processing (12_PPPOsm) with track map"""
    b = main_window("fig27", "12_PPPOsm.bnc", 14)
    click(b.main, *OPEN_MAP)
    m = wait_window("BNC: Map View", timeout=60)
    place(m, X0 + 270, Y0 + 110, 900, 640)
    time.sleep(10)
    activate(b.main)
    click(b.main, *START)
    time.sleep(90)
    activate(m)
    shot("Figure27", frame())
    b.stop()


def fig28():
    """Combine Corrections panel (17_Combi, not started)"""
    panel("fig28", "Figure28", "17_Combi.bnc", 15, keys=[NO_UPLOAD])


def fig29():
    """live: INTERNAL PPP from the combination (18_CombiPPP, no upload)"""
    panel("fig29", "Figure29", "18_CombiPPP.bnc", 11, 3, keys=[NO_UPLOAD], live=True, run=1200)


def fig30():
    """Upload Corrections panel (16_Upload, not started)"""
    panel("fig30", "Figure30", "16_Upload.bnc", 16)


def fig31():
    """Custom Transformation Parameters dialog"""
    b = main_window("fig31", "16_Upload.bnc", 16)
    click(b.main, *CUSTOMTRAFO)
    d = wait_window("Custom Transformation")
    time.sleep(1)
    activate(d)
    wshot("Figure31", d)
    b.stop()


def fig32():
    """Upload Corrections of the combination (17_Combi, not started)"""
    panel("fig32", "Figure32", "17_Combi.bnc", 16)


def fig33():
    """Upload Ephemeris panel (19_UploadEph, not started)"""
    panel("fig33", "Figure33", "19_UploadEph.bnc", 17)


def fig34_35():
    """live: throughput (34) and latency (35) of 20 igs-ip.net streams"""
    coord = {}
    try:   # coordinates from the public sourcetable
        req = urllib.request.Request("http://igs-ip.net:2101/", headers={"Ntrip-Version": "Ntrip/2.0"})
        for line in urllib.request.urlopen(req, timeout=20).read().decode("latin-1").splitlines():
            f = line.split(";")
            if f[0] == "STR" and f[1] in MANY:
                coord[f[1]] = (f[8], float(f[9]), float(f[10]))
    except OSError:
        pass
    mps = ";".join("//Example:Configs@igs-ip.net:2101/%s RTCM_3.3 %s %.2f %.2f no 2"
                   % ((m,) + coord.get(m, ("XXX", 0.0, 0.0))) for m in MANY)
    b = main_window("fig34_35", "22_Empty.bnc", 0, 1, live=True, keys=[
        ("mountPoints", mps), ("miscMount", "ALL"), ("miscIntr", "1 min")])
    run_and_wait(b, 150)
    crop_file(shot("_fig34_full", frame()), "Figure34", LOG_CANVAS)
    click(b.main, *LATENCY_TAB)
    time.sleep(2)
    crop_file(shot("_fig35_full", frame()), "Figure35", LOG_CANVAS)
    b.stop()


# --- RINEX QC and editing ---------------------------------------------------

def fig11_13():
    """RINEX QC plot windows: availability (11), multipath (12), SNR (13)"""
    b = main_window("fig11_13", "05_RinexQC.bnc", 4)
    click(b.main, *START)
    wins = wait_window("BRUX00BEL_R_20250750000_01D_30S_MO", timeout=600, count=3)
    time.sleep(5)
    for w in [b.main] + wins:
        xdo("windowminimize", w)
    time.sleep(1)
    sizes = {w: shoot.geometry(w)[2:] for w in wins}
    avail = min(wins, key=lambda w: sizes[w][0] * sizes[w][1])   # the smallest window
    skyplots = [w for w in wins if w != avail]                   # in order: multipath, SNR
    for name, w in [("Figure11", avail), ("Figure12", skyplots[0]), ("Figure13", skyplots[1])]:
        activate(w)
        place(w, 20, 40)
        xdo("windowsize", w, *shoot.geometry(w)[2:])   # forces a repaint
        time.sleep(4)
        shot(name, frame())
        xdo("windowminimize", w)
        time.sleep(1)
    b.stop()


def fig14():
    """RINEX Editing Options dialog"""
    b = main_window("fig14", "04_RinexConcat.bnc", 4, keys=[
        ("reqcRnxVersion", "4"), ("reqcSampling", "30 sec"), ("reqcRunBy", "Andrea Stuerze"),
        ("reqcUseObsTypes", "E:C1C E:L1C E:D1C E:S1C E:C5Q E:L5Q E:D5Q E:S5Q"),
        ("reqcComment", "Extracting some Galileo Observations \\n from multi GNSS RINEX file"),
        ("reqcNewMarkerName", "")])
    click(b.main, *EDITOPTIONS)
    d = wait_window("RINEX Editing Options")
    activate(d)
    place(d, 300, 200)
    wshot("Figure14", d)
    b.stop()


def fig15():
    """RINEX concatenation with its logfile"""
    b = main_window("fig15", "04_RinexConcat.bnc", 4)
    click(b.main, *START)
    log = os.path.join(b.dir, "Output", "RinexConcat.log")
    for _ in range(120):
        if os.path.exists(log) and len(open(log).read().splitlines()) >= 20:
            break
        time.sleep(1)
    time.sleep(3)
    v = subprocess.Popen(["python3", os.path.join(shoot.HERE, "viewer.py"), log, "88", "22"],
                         env=dict(shoot.XENV, LC_ALL="C.UTF-8"))
    w = wait_window("RinexConcat.log")
    place(w, X0 + 420, Y0 + 260)
    shot("Figure15", frame())
    v.terminate()
    b.stop()


def fig17():
    """SP3 comparison plots (scripts/compareSP3Plot.pl, Galileo)"""
    d = os.path.join(shoot.WORK, "run", "fig17")
    subprocess.run(["rm", "-rf", d])
    os.makedirs(os.path.join(d, "Output"))
    os.symlink(os.path.join(BNC_ROOT, "Example_Configs", "Input"), os.path.join(d, "Input"))
    subprocess.run([BNC, "--nw", "--conf", os.path.join(BNC_ROOT, "Example_Configs", "21_CompareSp3.bnc")],
                   cwd=d, env=dict(BNCENV, QT_QPA_PLATFORM="offscreen"), capture_output=True, timeout=600)
    log = os.path.join(d, "Output", "Sp3Comparison.log")
    subprocess.run(["perl", "-I", os.path.join(BNC_ROOT, "scripts"),
                    os.path.join(BNC_ROOT, "scripts", "compareSP3Plot.pl"), "--keepImages",
                    "--plotTypes", "RAO,CLK", "-l", log], cwd=d, stdin=subprocess.DEVNULL,
                   capture_output=True, timeout=600)
    pngs = [os.path.join(d, "Sp3Comparison_%s_E.png" % t) for t in ("RADIAL", "ALONG", "OUT", "CLKRED")]
    path = os.path.join(shoot.OUT, "Figure17.png")
    subprocess.run(["montage"] + pngs + ["-tile", "2x2", "-geometry", "+10+10", "-background",
                    "white", path], check=True)
    subprocess.run(["convert", path, "-bordercolor", "black", "-border", "1", path], check=True)
    saved(path)


# --- Add Stream dialogs ------------------------------------------------------

CASTER_KEYS = [("casterUrlList", "http://Example:Configs@igs-ip.net:2101"), ("ntripVersion", "2")]


def add_stream_dialog(job, button, keys=()):
    b = main_window(job, "22_Empty.bnc", 0, keys=keys)
    click(b.main, *ADDSTREAM)
    d = wait_window("Add Stream")
    time.sleep(1.5)
    activate(d)
    click(d, *button)
    return b


def caster_dialog(job):
    b = add_stream_dialog(job, ADD_CASTER, keys=CASTER_KEYS)
    d = wait_window("Add Streams from Caster")
    activate(d)
    place(d, 100, 100, 1400, 830)
    return b, d


def fig37():
    """Add Stream dialog"""
    b = main_window("fig37", "22_Empty.bnc", 0)
    click(b.main, *ADDSTREAM)
    d = wait_window("Add Stream")
    activate(d)
    place(d, 300, 200)
    wshot("Figure37", d)
    b.stop()


def fig38():
    """Casters table (Select Broadcaster)"""
    b, d = caster_dialog("fig38")
    time.sleep(1.5)
    click(d, 1356, 23)             # 'Show' casters table
    w = wait_window("Select Broadcaster", timeout=60)
    time.sleep(3)
    activate(w)
    place(w, 150, 150, 960, 900)
    time.sleep(1)
    wshot("Figure38", w)
    b.stop()


def fig39_40():
    """Sourcetable of igs-ip.net (39) and map of its streams (40)"""
    b, d = caster_dialog("fig39_40")
    click(d, 1176, 806)            # 'Get table'
    time.sleep(8)
    wshot("Figure39", d)
    before = visible_windows()
    click(d, 1091, 806)            # 'Map'
    m = new_window(before)
    activate(m)
    place(m, 200, 150, 1360, 900)
    time.sleep(3)
    wshot("Figure40", m)
    b.stop()


def fig41():
    """Add Stream from Serial Port dialog"""
    b = add_stream_dialog("fig41", ADD_SERIAL)
    d = wait_window("Serial Port")
    activate(d)
    for ii, text in enumerate(["MYROVER", "RTCM_3", "51.2", "8.52", "DEU", "/dev/ttyS0"]):
        if ii:
            key(d, "Tab")
        typetext(d, text)
    time.sleep(1)
    wshot("Figure41", d)
    b.stop()


JOBS = {n: f for n, f in globals().items() if n.startswith("fig") and callable(f)}
