#ifndef CMODBUSSLAVE_H
#define CMODBUSSLAVE_H

#include <QObject>
#include "ModbusBackend.h"
#include <QTcpServer>
#include "ModbusRepository.h"
#include <QTimer>

enum eModbusCCTrainTypes
{
    MODBUS_CC_TRAIN_TYPE_MR63 = 63,
    MODBUS_CC_TRAIN_TYPE_MR73 = 73,
    MODBUS_CC_TRAIN_TYPE_MPM10 = 10,
    MODBUS_CC_TRAIN_TYPE_MAINTENANCE = 0,
    MODBUS_CC_TRAIN_TYPE_INVALID_ATS_OFFLINE = 98,
    MODBUS_CC_TRAIN_TYPE_INVALID_SERVICE_REBOOT = 97,
    MODBUS_CC_TRAIN_TYPE_INVALID_NOT_UPDATED = 99,
    MODBUS_CC_TRAIN_TYPE_INVALID_SACL_OFFLINE = 96,

    MODBUS_CC_TRAIN_TYPE_MAX_VALUE
};


class CModbusCCMgr : public CModbusBackend
{
    Q_OBJECT
public:
    explicit CModbusCCMgr(CModbusRepository *Repo, int ModbusPort, int DevID);
    virtual ~CModbusCCMgr();

    int StartModbusCCServer();
    bool IsModbusConnected();



    virtual void RegistersDatabaseUpdated(quint16 StartAddress, quint16 Length);
    virtual void ModbusRequestException(quint8 ExceptionCode, quint8 FctCode);



    //Helper functions
    QList<qint16> GetZT1TrainComposition();
    QList<qint16> GetZT2TrainComposition();
    bool GetZT1InhibitionFlag();
    bool GetZT2InhibitionFlag();
    qint16 GetZT1TrainType();
    qint16 GetZT2TrainType();
    
private:
    QTcpServer *mModbusServer;
    int mModbusPort;
    QTimer *mZTWatchdogTimer, *mCCWatchdogTimer;
    qint16 mZTWatchdog;
    qint16 mCCWatchdogState;
    bool mCCLinkState;
    QDateTime *mLastDateTime;

    int ResetCCRepository();

signals:
    void RepoHasChanged();
    void ModbusCCConnected();
    void ModbusCCDisconnected();
    void ModbusCCLinkLost();
    void ModbusCCLinkRecovered();
    void ModbusDateTimeReceived(QDateTime *DateTime);
    
public slots:
    void NewModbusConnection();
    void ConnectionLost();
    void ModbusZTWatchdogTimeout();
    void ModbusCCWatchdogTimeout();
};

#endif // CMODBUSSLAVE_H
