"""
@file {{filename}}_lmsg.py

@brief  {{filename}} lmsg Classes

This file contains the declaration of the message classes generated by the Lions Compiler.

@details
This file was generated by the Lions Compiler (https://github.com/ItsNotSoftware/lions) on .
Modifying this file manually is not recommended as it may lead to unexpected behavior.

@note
Generated files should not be manually edited.

@authored by Lions Compiler
"""

from .lions import LMsg, Header
import struct

# msg ids 
{% for msg in msgs %}MSG_ID_{{ msg.name | upper }} = {{ msg.id }}
{% endfor %}

# msg periods
{% for msg in msgs %}MSG_PERIOD_{{ msg.name | upper}} = {{ msg.period }}
{% endfor %}

{% for msg in msgs %}
class {{ msg.name | capitalize }}Msg:
    def __init__(self, {% for field in msg.fields %}{{ field.name }}: {{ field.type }}{% if not loop.last %}, {% endif %}{% endfor %}):
        self.header = Header()
        {% for field in msg.fields %}self.{{ field.name }} = {{ field.name }}
        {% endfor %}
    @staticmethod
    def from_lmsg(msg: LMsg) -> "{{ msg.name | capitalize }}Msg":
        {% for field in msg.fields %}
        {% if field.type == 'str' %}{{ field.name }} = msg.payload[{{ field.start }}:{{ field.start + field.size }}].decode('utf-8')
        {% else %}{{ field.name }} = struct.unpack("{{ field.buff_type }}", msg.payload[{{ field.start }}:{{ field.start + field.size }}])[0]{% endif %}{% endfor %} 
        instance = {{ msg.name | capitalize }}Msg({% for field in msg.fields %}{{ field.name }}{% if not loop.last %}, {% endif %}{% endfor %})
        instance.header = msg.header

        return instance

    def encode(self, src: int, dst: int, next_hop: int) -> LMsg:
        msg = LMsg({{ msg.payload_size }})
        msg.header.src = src
        msg.header.dst = dst
        msg.header.next_hop = next_hop
        msg.header.msg_id = {{ msg.id }} 
        {% for field in msg.fields %}
        {% if field.type == 'str' %}msg.payload[{{ field.start }}:{{ field.start + field.size }}] = self.{{ field.name }}.encode('utf-8')
        {% else %}msg.payload[{{ field.start }}:{{ field.start + field.size }}] = struct.pack("{{ field.buff_type }}", self.{{ field.name }}){% endif %} {% endfor %}
        msg.calculate_checksum()

        return msg


    def __str__(self) -> str:
        s = "\n[{{msg.name | capitalize}}Msg]\n"
        s += f"    {self.header}\n\n"
        {% for field in msg.fields %}s += f"    {{ field.name }}: {self.{{field.name}}}\n" 
        {% endfor %}
        return s
{% endfor %}


