# control.py

import logging
import time


def register(app, ctx) -> None:
    @app.route('/nudge_x/<dist>')
    def nudge_x(dist: str) -> str:
        dist = float(dist)
        logging.info('NUDGE_X %s', dist)
        ctx.ad.util_nudge_x(dist)
        return 'Moved'

    @app.route('/nudge_y/<dist>')
    def nudge_y(dist: str) -> str:
        dist = float(dist)
        logging.info('NUDGE_Y %s', dist)
        ctx.ad.util_nudge_y(dist)
        return 'Moved'

    @app.route('/home')
    def home() -> str:
        logging.info('HOME')
        ctx.ad.util_home()
        return 'Homed'

    @app.route('/move_xy/<x>/<y>')
    def move_xy(x: str, y: str) -> str:
        x, y = float(x), float(y)
        logging.info('MOVE_XY %s %s', x, y)
        ctx.ad.i_move(x, y)
        return 'Moved'

    @app.route('/move_to/<x>/<y>')
    def move_to(x: str, y: str) -> str:
        x, y = float(x), float(y)
        logging.info('MOVE_TO %s %s', x, y)
        ctx.ad.i_moveto(x, y)
        return 'Moved'

    @app.route('/set_home')
    def set_home() -> str:
        logging.info('SET_HOME')
        ctx.ad.util_align()
        return 'Home position set'

    @app.route('/toggle_pen')
    def toggle_pen() -> str:
        logging.info('TOGGLE_PEN')
        ctx.ad.util_toggle()
        return 'Pen toggled'

    @app.route('/cycle_pen')
    def cycle_pen() -> str:
        logging.info('CYCLE_PEN')
        ctx.ad.util_cycle()
        return 'Pen cycled'

    @app.route('/disable_motors')
    def disable_motors() -> str:
        logging.info('disable_motors')
        ctx.ad.util_motors_off()
        return 'Motors disabled'

    @app.route('/enable_motors')
    def enable_motors() -> str:
        logging.info('enable_motors')
        ctx.ad.util_motors_on()
        return 'Motors enabled'

    @app.route('/prime')
    def prime() -> str:
        logging.info('priming motors')
        ctx.ad.util_nudge_x(2)
        ctx.ad.util_nudge_y(2)
        time.sleep(0.25)
        ctx.ad.util_motors_off()
        time.sleep(0.25)
        ctx.ad.util_motors_on()
        return 'Position primed'
