/**
 *
 *  gsd_TcpPlugin.h
 *
 */

#pragma once

#include <drogon/plugins/Plugin.h>
#include "TCPClient.hpp"
#include "Util/TimeTicker.h"
#include "Poller/Timer.h"
#include "dataTypeList.h"
#include "md5.h"
#include "uuid.hpp"
#include "Util/SqlPool.h"
#include "expel.h"
#include <drogon/drogon.h>

using namespace toolkit;

namespace gsd
{

class TcpPlugin : public drogon::Plugin<TcpPlugin>
{
  public:
    TcpPlugin() {}
    /// This method must be called by drogon to initialize and start the plugin.
    /// It must be implemented by the user.
    virtual void initAndStart(const Json::Value &config) override;

    /// This method must be called by drogon to shutdown the plugin.
    /// It must be implemented by the user.
    virtual void shutdown() override;
    
    /**
     * @description: 启动任务
     * @return {*}
     */    
    void StartTask();

    /**
     * @description: 发送心跳数据
     * @return {*}
     */    
    void SendHeartbeatData();

    /**
     * @description: 登录Netty
     * @return {*}
     */    
    void TCPLoginNetty();

    /**
     * @description: 获取登录结果
     * @return {*}
     */    
    bool getLoginNetty();

    /**
     * @description: 监听Netty的数据
     * @param {Ptr} &buf
     * @return {*}
     */    
    void ListenNettyData(const Buffer::Ptr &buf);

    /**
     * @description: 获取与Netty的通讯是否存活
     * @return {*}
     */    
    bool getAlive();

    /**
     * @description: 发送请求
     * @param {string} RequestId  UUID
     * @param {string} CommandEnum 命令枚举
     * @param {string&} data  数据
     * @param {function<void(std::string)>} t 回调函数（请求结果, 返回的数据）
     * @return {*}
     */    
    void sendRequest(std::string RequestId,std::string CommandEnum, std::string& data,function<void(int, std::string)> t);

  private:
    
    // TCP对象
    TCPClient::Ptr tcpClient = nullptr;
    // 心跳定时器
    Timer::Ptr HeartbeatTimer = nullptr;

    bool TcpNettyLogin = false;

    // 线程池
    std::shared_ptr<ThreadPool> pool = nullptr;
};

}
