#include "common/dsp/complex.h"
#include "limesdr_dev.h"
#include <lime/LimeSuite.h>
#include <logger.h>
#include <string>

namespace satdump
{
    namespace ndsp
    {
        void LimeSDRDevBlock::mainThread_rx()
        {
            int sample_buffer_size = std::min<int>(samplerate / 250, 1e6);

            while (thread_should_run_rx)
            {
                for (int ch = 0; ch < rx_ch_number; ch++)
                {
                    DSPBuffer oblk = outputs[ch].fifo->newBufferSamples(sample_buffer_size, sizeof(complex_t));

                    int v = LMS_RecvStream(&rx_streams[ch], oblk.getSamples<complex_t>(), sample_buffer_size, nullptr, 1000);

                    oblk.size = v;
                    if (v > 0)
                        outputs[ch].fifo->wait_enqueue(oblk);
                    else
                        outputs[ch].fifo->free(oblk);
                }
            }
        }

        void LimeSDRDevBlock::mainThread_tx()
        {
            bool terminate = false;

            while (1)
            {
                if (terminate)
                    break;

                for (int ch = 0; ch < rx_ch_number; ch++)
                {
                    DSPBuffer iblk = inputs[ch].fifo->wait_dequeue();

                    if (iblk.isTerminator())
                    {
                        inputs[ch].fifo->free(iblk);
                        terminate = true;
                        break;
                    }

                    int status = LMS_SendStream(&tx_streams[ch], iblk.getSamples<complex_t>(), iblk.size, nullptr, 1000);
                    if (status == 0)
                        logger->error("LimeSDR TX Timeout!");
                    else if (status <= 0)
                        logger->error("LimeSDR TX Error! %d", status);
                    else if (status != iblk.size)
                        logger->error("LimeSDR Stream dropped!");

                    inputs[ch].fifo->free(iblk);
                }
            }
        }
    } // namespace ndsp
} // namespace satdump