#include "LiveStreamService.h"

#include "./LiveStreamPushModule/LiveStreamPushModule.h"

CLiveStreamService *CLiveStreamService::s_piInstance = nullptr;

CLiveStreamService::CLiveStreamService()
{
    m_nPort = 8554;
    m_nMaxStreamNum = 10;

    m_piModule = new CLiveStreamPushModule;
    ReadConfig();
}

CLiveStreamService::~CLiveStreamService()
{

}

void CLiveStreamService::ReadConfig()
{

}

bool CLiveStreamService::PushCVMatToStream(const std::string &strStreamName,const cv::Mat &iMat,euint32 nFramerate)
{
    if(!m_piModule->IsInService())
    {
        m_piModule->StartLiveStreamService(m_nPort);
    }

    if(strStreamName.empty() || iMat.empty() || nFramerate == 0)
        return false;

    if(m_mapNameToHandler.count(strStreamName) == 0)
    {
        if(m_mapNameToHandler.size() >= m_nMaxStreamNum)
        {
            return false;
        }

        LiveStreamParam iParam;
        iParam.nFrameRate = nFramerate;
        iParam.nWidth = iMat.cols;
        iParam.nHeight = iMat.rows;
        iParam.strStreamName = strStreamName;
        iParam.strStreamInfo = "";

        CLiveStreamHandler *pHandler = m_piModule->AddOneLiveStream(iParam);
        if(pHandler)
        {
            m_mapNameToHandler[strStreamName] = pHandler;
        }
        else
        {
            return false;
        }
    }

    CLiveStreamHandler *pHandler = m_mapNameToHandler[strStreamName];
    if(nullptr == pHandler)
        return false;

    return m_piModule->PushImage(pHandler,iMat);
}

bool CLiveStreamService::StartSaveStreamToFile(const string &strStreamName, const string &strFileName)
{
    if(!m_piModule->IsInService())
    {
        return false;
    }

    if(strStreamName.empty() || strFileName.empty())
        return false;

    if(m_mapNameToHandler.count(strStreamName) == 0)
    {
        return false;
    }

    CLiveStreamHandler *pHandler = m_mapNameToHandler[strStreamName];
    if(nullptr == pHandler)
        return false;

    return m_piModule->StartSaveToFile(pHandler,strFileName);
}

bool CLiveStreamService::StopSaveStreamToFile(const string &strStreamName)
{
    if(!m_piModule->IsInService())
    {
        return false;
    }

    if(strStreamName.empty())
        return false;

    if(m_mapNameToHandler.count(strStreamName) == 0)
    {
        return false;
    }

    CLiveStreamHandler *pHandler = m_mapNameToHandler[strStreamName];
    if(nullptr == pHandler)
        return false;

    return m_piModule->StopSaveToFile(pHandler);
}
