
#ifndef _MEDIAWEBSOCKETPROTOCOL_H_
#define _MEDIAWEBSOCKETPROTOCOL_H_

#include "MFSPublic.h"
#include "MediaClientConnection.h"
#include "AppSetting.h"

namespace mfs
{
 
class MediaWebSocketProtocol: public MediaClientConnection
{
    public:
    virtual int writeData(char* data, int dataLen) override;
    virtual void sendMessage(const char* data, int dataLen) override;
    virtual void generatePackageHead(int dataLen, char* head, int& headLen) override;
    public:
    MediaWebSocketProtocol(std::shared_ptr<uvw::Loop> loop, std::shared_ptr<uvw::TCPHandle> client, const std::string& name)
    :MediaClientConnection(loop, client, name)
    {
        _streamInfo.targetType = "1";
#if CONVERT_AAC
        _adpcmState = std::make_shared<adpcm_state>();
        _pcm2aac = std::make_shared<Pcm2AAC>();
        _pcm2aac->Init(8000, AV_SAMPLE_FMT_S16, 1);
#endif

        http_parser_init(&_parser, HTTP_REQUEST);
        _parser.data = this;
        // LOG_DEBUG << "_isTalk="<<_isTalk<<", _isPlayback="<<_isPlayback<<",_isSaveTalk="<<_isSaveTalk<<LOG_ENDL;
    }
    private:
#if CONVERT_AAC
        std::shared_ptr<adpcm_state> _adpcmState;
        std::shared_ptr<Pcm2AAC> _pcm2aac;
    std::ofstream  testfilestream;
#endif
    http_parser _parser;
    
    int _websocketOffset = 0;
    char _mask[4] = {0};
    int _websocketStatus = 0;
    int _currentOpcode = 0;

    int _logWriteFlag=0;
    int _logReadFlag=0;


    int parseWebSocketHead();
    int parseWebSocketBody();
    virtual int parse(int length) override;
    virtual int recvHandShakeData() override;
    virtual int sendHandShakeData() override;

    static http_parser_settings callbackSetting;
    static int onUrl(http_parser* parser, const char* data, size_t);
    static int onHeaderField(http_parser* parser, const char* data, size_t);
    static int onHeaderValue(http_parser* parser, const char* data, size_t);
    static int onHeadersComplete(http_parser* parser);

    
    virtual void alogd(const std::string& message, const std::string& fileName, const int line, const std::string& functionName)  override {
        BaseProtocol::alogd(std::string()+"["+_url+"]"+message, fileName, line, functionName);
    }
    virtual void aloge(const std::string& message, const std::string& fileName, const int line, const std::string& functionName)  override {
        BaseProtocol::aloge(std::string()+"["+_url+"]"+message, fileName, line, functionName);
    }
    virtual void alogv(const std::string& message, const std::string& fileName, const int line, const std::string& functionName)  override {
        BaseProtocol::alogv(std::string()+"["+_url+"]"+message, fileName, line, functionName);
    }
};

}




#endif // _MEDIAWEBSOCKETPROTOCOL_H_