#include "grifo_exciter_if.h"

#include "grifo_ctrlink_common.h"

#include <stdint.h>

//Make code common with Synth? So far is a copy and replace
namespace grifo_fw
{

enum fid_exicter_t
{
    exciter_lo_freq=0x50,
    excuter_upc=0x80,
};


static ctrlink_blob_t* blob(ctrlink_blob_t* b)
{
    return b==0 ? ctrlink_exciter_bus : b;
}

template<typename T_> static T_* exciter_msg_alloc_size(ctrlink_blob_t* ld, fid_exicter_t fid, unsigned int size, T_* msg=0, ctrlink_pingpong_t pingpong=ctrlink_pingpong_auto, ctrlink_append_mode_t mode=ctrlink_append_write)
{
    ld=blob(ld); //ld=ctrlink_exciter_bus;

    unsigned int payload_size=size; //sizeof(T_);
    uint32_t dst=ctrlink_address(ctrlink_exciter, static_cast<function_id_t>(fid), pingpong); //ctrlink_pingpong_auto);

    T_* m=reinterpret_cast<T_*>(ctrlink_append_raw_message(ld, dst, mode, msg, payload_size));
    return m;
}

template<typename T_> static T_* exciter_msg_alloc(ctrlink_blob_t* ld, fid_exicter_t fid, T_* msg, ctrlink_pingpong_t pp, ctrlink_append_mode_t mode=ctrlink_append_write)
{
    return exciter_msg_alloc_size(ld, fid, sizeof(T_), msg, pp, mode);
}

int exciter_append_status_request(ctrlink_blob_t* ld)
{
    ld=blob(ld); //ld=ctrlink_exciter_bus;

    return ctrlink_append_status_request(ld, ctrlink_exciter);
}

union exciter_ctrl_t
{
    struct {
        unsigned int rf_out: 2;
        unsigned int spare0: 2;
        unsigned int upc_sel: 2;
        unsigned int spare1: 2;
        unsigned int freq: 3;
        unsigned int spare: 5;
    } str;
    uint32_t raw;
};


int exciter_append_upc_command_operative_message(ctrlink_blob_t* ld, unsigned int freq_upc, exciter_upc_sel_t upc_sel, exiter_rf_out_t rf_out, ctrlink_pingpong_t pingpong)
{
    exciter_ctrl_t* m=exciter_msg_alloc<exciter_ctrl_t>(ld, excuter_upc, 0, pingpong);
    m->raw=0;

    m->str.rf_out=rf_out;
    m->str.upc_sel=upc_sel;
    m->str.freq=freq_upc;

    return 0;
}

int exciter_append_upc_command_asynch_message(ctrlink_blob_t* ld, unsigned int freq_upc, exciter_upc_sel_t upc_sel, exiter_rf_out_t rf_out)
{
    return exciter_append_upc_command_operative_message(ld, freq_upc, upc_sel, rf_out, ctrlink_pingpong_aynch);
}

int exciter_append_lo_frequency_operative_message(ctrlink_blob_t* ld, unsigned int num_values, const unsigned int* frq /*[num_values]*/, ctrlink_pingpong_t pingpong)
{
    ld=blob(ld); //ld=ctrlink_exciter_bus;

    return ctrlink_append_lo_frequency_operative_message(ld, ctrlink_exciter, num_values, frq, pingpong);
}

int exciter_append_lo_frequency_asynch_message(ctrlink_blob_t* ld, unsigned int frq)
{
    ld=blob(ld); //ld=ctrlink_exciter_bus;

    return ctrlink_append_lo_frequency_asynch_message(ld, ctrlink_exciter, frq);
}


}//namespace
