# Copyright (C) 2022 Justin Schuh <code@justinschuh.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.

[gcode_macro _km_save_state]
description: Tracks gcode state.
variable_state_set: {}
variable_is_ephemeral: 0
gcode:
  {% if params.SAVE|int %}
    {% set dummy = state_set.__setitem__(params.NAME, None) %}
  {% else %}
    {% set dummy = state_set.__delitem__(params.NAME) %}
  {% endif %}
  SET_GCODE_VARIABLE MACRO=_km_save_state VARIABLE=is_ephemeral VALUE="{
    1 if state_set|length > 0 else 0 }"

[gcode_macro save_gcode_state]
description: Wraps SAVE_GCODE_STATE to track persistence state.
  Usage: See Klipper documentation
rename_existing: _KM_SAVE_GCODE_STATE
gcode:
  _KM_SAVE_GCODE_STATE {rawparams}
  {% set NAME = params.NAME|default("default") %}
  _km_save_state NAME={NAME} SAVE=1

[gcode_macro restore_gcode_state]
description: Wraps RESTORE_GCODE_STATE to track persistence state.
  Usage: See Klipper documentation
rename_existing: _KM_RESTORE_GCODE_STATE
gcode:
  _KM_RESTORE_GCODE_STATE {rawparams}
  {% set NAME = params.NAME|default("default") %}
  _km_save_state NAME={NAME} SAVE=0

[gcode_macro _abort_on_gcode_state]
gcode:
  {% set save_state = printer["gcode_macro _km_save_state"] %}
  {% if save_state.is_ephemeral %}
    {action_raise_error("Encountered unexpected save state " +
                          save_state.state_set|list|sort|string)}
  {% endif %}
