"""Hardware RMT v2 Infrared Universal Remote & GNSS Field Companion.

Demonstrates Phase 4 `hal.ir` (38 kHz hardware-carrier NEC TX without CPU bit-banging)
and `hal.gnss` (streaming C NMEA/UBX fixed-point satellite fix parser):
- Works out of the box on `m5stack_cardputer_adv`, `m5stack_cardputer`,
  `m5stack_stickc_plus2`, `m5stack_atoms3`, and `m5stack_nanoc6`!

Run locally:
    pylotos-sim examples/ir_universal_remote.py --board m5stack_cardputer_adv --port 8080
"""

import hal
import pylotos.ui as ui

hal.ir.open(carrier_hz=38000)
hal.gnss.open(baudrate=9600)

st = ui.State(
    ir_addr=0x04,
    ir_sent=0,
    last_cmd="IDLE",
    sats=0,
    lat_deg="0.00000",
    lon_deg="0.00000",
    alt_m=0,
)


def _send_nec(label, cmd):
    hal.ir.tx_nec(int(st.ir_addr) & 0xFF, int(cmd) & 0xFF)
    st.ir_sent = st.ir_sent + 1
    st.last_cmd = "{} (0x{:02X})".format(label, cmd)
    hal.beep(980, 25, 35)
    app.toast("IR TX: " + st.last_cmd)


app = ui.App(
    "IR & GNSS",
    state=st,
    screens=[
        ui.Screen(
            "IR Remote",
            icon="bolt",
            children=[
                ui.StatusBadge("Last IR", st.bind("last_cmd"), tone="info"),
                ui.Card(
                    "NEC 38 kHz Controls",
                    children=[
                        ui.NumberField("NEC Address", st.bind("ir_addr"), min=0, max=255, step=1),
                        ui.Button("Power Toggle", on_click=lambda: _send_nec("POWER", 0x08), shortcut="p"),
                        ui.Button("Volume +", on_click=lambda: _send_nec("VOL+", 0x02), shortcut="+"),
                        ui.Button("Volume -", on_click=lambda: _send_nec("VOL-", 0x03), shortcut="-"),
                        ui.Button("Mute", on_click=lambda: _send_nec("MUTE", 0x09), shortcut="m"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "GNSS Fix",
            icon="cloud",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Satellites", st.bind("sats"), accent="cyan"),
                        ui.Metric("Altitude", st.bind("alt_m"), unit="m", accent="gold"),
                    ],
                ),
                ui.Card(
                    "Coordinates (Fixed-Point e7)",
                    children=[
                        ui.KeyValue("Latitude", st.bind("lat_deg")),
                        ui.KeyValue("Longitude", st.bind("lon_deg")),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(1000)
def _poll_gnss():
    fix = hal.gnss.poll()
    if fix.get("valid"):
        st.sats = int(fix.get("sats", 0))
        st.lat_deg = "{:.5f}".format(int(fix.get("lat_e7", 0)) / 10000000.0)
        st.lon_deg = "{:.5f}".format(int(fix.get("lon_e7", 0)) / 10000000.0)
        st.alt_m = int(fix.get("alt_mm", 0)) // 1000


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.ir.close()
        hal.gnss.close()
