/**
 * @file {{filename}}_lmsg.cpp
 *
 * @brief Implementation of {{filename}}_lmsg.hpp Classes
 * 
 * This file contains the implementation of the message classes generated by the Lions Compiler.
 * 
 * @details
 * This file was generated by the Lions Compiler (https://github.com/ItsNotSoftware/lions) on {{date}}.
 * Modifying this file manually is not recommended as it may lead to unexpected behavior.
 * 
 * @note
 * Generated files should not be manually edited.
 * 
 * @author Lions Compiler
*/

#include "{{filename}}_lmsg.hpp"

#include <algorithm>
#include <utility>

namespace lions {
{% for msg in msgs %} 
{{ msg.name | capitalize }}Msg::{{ msg.name | capitalize }}Msg({% for field in msg.fields %}const {{ field.type }} {{ field.name }}{% if not loop.last %}, {% endif %}{% endfor %})
    {% if msg.fields|length != 0 %}: {% for field in msg.fields %}{{ field.name }}({{ field.name }}){% if not loop.last %}, {% endif %}{% endfor %}{% endif %} {}

{{ msg.name  | capitalize }}Msg::{{ msg.name  | capitalize }}Msg(const LMsg &msg) { {# Constructors #}
    header = std::move(msg.header);
    {% for field in msg.fields %} 
    {% if field.type == 'std::string' %}{{ field.name }} = std::string(reinterpret_cast<const char*>(&msg.payload[{{ field.start }}]), {{ field.size }}); 
    {% else %}{{ field.name }} = *reinterpret_cast<const {{ field.type }}*>(&msg.payload[{{ field.start }}]); {% endif %} {% endfor %}
}

LMsg {{ msg.name  | capitalize }}Msg::encode(const uint8_t src, const uint8_t dst, const uint8_t next_hop) { {# encode #}
    LMsg msg({{ msg.payload_size }});

    msg.header.src = src;
    msg.header.dst = dst;
    msg.header.next_hop = next_hop;
    msg.header.msg_id = static_cast<uint8_t>(msg_id::{{msg.name | upper}});

    {% for field in msg.fields%}{% if field.type == 'std::string' %}std::copy({{ field.name }}.begin(), {{ field.name }}.end(), msg.payload + {{ field.start }});
    msg.payload[{{field.start}} + {{field.name}}.size()] = '\0'; // terminate string
    {% else %}*reinterpret_cast<{{ field.type }}*>(&msg.payload[{{ field.start }}]) = {{ field.name }};{% endif %}
    {% endfor %}msg.calculate_checksum();
    
    return msg;
}
{% endfor %}
}  // namespace lions
