/*
 * Copyright (c) 2024 Markus Lehr.
 * 
 *
 * SPDX-License-Identifier: Owend property of Markus Lehr
 * 
 */

#ifndef RTS_INCLUDE_RTSMONITORINGTASK_H_
#define RTS_INCLUDE_RTSMONITORINGTASK_H_

#include "RTSCoproHelper.h"
#include "RTSMonFrame.h"
#include <pthread.h>
#include <map>
#include <string>
#include <atomic>

#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/eventfd.h>
#include <sys/poll.h>
#include <fcntl.h>
#include <regex.h>
#include <sched.h>
#include <signal.h>

#include <inttypes.h>
#include <termios.h>

#include <stdlib.h>
#include <stdint.h>

#include <errno.h>
#include <error.h>
#include <signal.h>
#include <stdio.h>



#define NB_BUF 1


typedef struct
{
    int bufferId, eventfd;
} rpmsg_sdb_ioctl_set_efd;
 
typedef struct
{
    int bufferId;
    uint32_t size;
} rpmsg_sdb_ioctl_get_data_size;



class RTSMonitoringTask
{
private:
    /* data */
    //lock Element

    //std::map<int, RTSMonFrame*> rtsMonFrames;
    pthread_t monThread;



    /* The file descriptor used to manage our TTY over RPMSG */
    int mFdRpmsg[2] = {-1, -1};
    RTSCoproHelper coproHelper;
    /* The file descriptor used to manage our SDB over RPMSG */
    int mFdSdbRpmsg = -1;

    rpmsg_sdb_ioctl_get_data_size q_get_data_size;

    rpmsg_sdb_ioctl_set_efd q_set_efd;

    int mefd[NB_BUF];
    void* mmappedData[NB_BUF];
    bool mfMappedData = false;
    struct pollfd mfds[NB_BUF];
    //uint8_t mDdrBuffAwaited = 1;
    uint32_t mNbUncompData=0;
    uint32_t mNbWrittenInFileData;
    uint32_t mNbUncompMB=0;
    uint32_t mNbPrevUncompMB=0;
    uint32_t mNbTty0Frame=0;
    char mByteBuffCpy[512];
    struct timeval tval_before, tval_after, tval_result;

    std::atomic_bool mRunThread= true;

public:
    std::string id;
    std::string monName;
    int samplerate;
    int sampleperiod;
    int downtime;
    std::string path;





public:

    RTSMonitoringTask(std::string id, std::string name, int samplerate, int sampleperiod, int downtime, std::string path);       
    ~RTSMonitoringTask();

    //static RTSMonitoringTask& Instance();
    bool Init();
    //bool CreateMonitoring(int id, std::string name, int samplerate, int sampleperiod, int downtime, std::string status);
    bool LoadFW();
    bool Start(); 
    bool Stop();

    int Open(std::string monfilename);
    bool Close();
    std::string Read();
    bool GetRunState();
    void SetRunState(bool runThread);

    std::string GetId();
    void SetId(std::string id);
    int GetRate();
    void SetRate(int rate);
    int GetPeriod();
    void SetPeriod(int period);
    int GetDowntime();
    void SetDowntime(int downtime);
    std::string GetPath();
    void SetPath(std::string path);

private: 
    static void* Run(void *obj);
    bool Load();

};



#endif /* RTS_INCLUDE_RTSMONITORINGTASK_H_ */

