{# SPDX-License-Identifier: MIT #}
{# Copyright © 2021 André Santos #}

{% import 'py/common.py.jinja' as G %}

{##############################################################################}
{# TIMER MACROS #}
{##############################################################################}

{% macro _on_timer(sm) -%}
if self._state == {{ G.STATE_ACTIVE }} and (stamp - self.time_state) >= {{ sm.timeout }}:
    {% if sm.reentrant_scope %}
{{ G.change_to_state(G.STATE_SAFE, returns=false)|indent(4, first=true) }}
    {%- else %}
{{ G.change_to_state(G.STATE_TRUE, returns=false)|indent(4, first=true) }}
    {%- endif %}
{%- endmacro %}


{##############################################################################}
{# MSG EVENT MACROS #}
{##############################################################################}

{% macro _on_msg(sm, event, topic) -%}
{% if event.event_type == G.EVENT_ACTIVATOR %}
{# after or after-until -#}
{{ G.activator_event(event, topic) }}
{%- elif event.event_type == G.EVENT_TERMINATOR %}
{# until or after-until -#}
{{ G.terminator_event(sm, event, topic) }}
{%- elif event.event_type == G.EVENT_BEHAVIOUR %}
{{ _behaviour(event, topic) }}
{%- else %}
assert False, 'unexpected event type: {{ event.event_type }}'
{%- endif %}
{%- endmacro %}

{% macro _behaviour(event, topic) -%}
    {% if event.activator %}
assert len(self.witness) >= 1, 'missing activator'
v_{{ event.activator }} = self.witness[0].msg
    {% endif %}
    {% call G.change_to_state_if(event.predicate, G.STATE_FALSE) %}
self.witness.append(MsgRecord('{{ topic }}', stamp, msg))
    {%- endcall %}
{%- endmacro %}


{##############################################################################}
{# RENDERED CODE #}
{##############################################################################}

{# assume: global('state_machine') #}
{% call(cb) G.state_machine(state_machine) -%}
    {% if cb == G.CALLBACK_TIMER -%}
{{ _on_timer(state_machine) }}
    {%- elif cb == G.CALLBACK_MSG -%}
{{ _on_msg(state_machine, varargs[0], varargs[1]) }}
    {%- else -%}
assert False, 'unexpected macro function type: {{ args }}'
    {%- endif %}
{%- endcall %}
