
#include <fstream>
#include "Rtp808Service.h"

namespace mfs
{
    // static Rtp808Service* _instance = nullptr;
    static std::map<int, Rtp808Service*> _instance;

    Rtp808Service* Rtp808Service::Instance(int port)
    {
        auto iter = _instance.find(port);
        if (iter != _instance.end())
        {
            return iter->second;
        }
        return nullptr;
    }

    Rtp808Service* Rtp808Service::SetupOnce(std::string& sername, int port, std::shared_ptr<uvw::Loop> loop)
    {
        auto ins = new Rtp808Service(sername, port, loop);
        _instance[port] = ins;
        return ins;
    }
    
    
    std::shared_ptr<Rtp808Protocol> Rtp808Service::GetRtpServiceByUrl(const std::string& url)
    {
        for (auto iter = _clients.begin(); iter != _clients.end(); iter++)
        {
            std::shared_ptr<Rtp808Protocol> ptr = std::static_pointer_cast<Rtp808Protocol>(*iter);
            if (ptr->getUrl() == url)
            {
                return ptr;
            }
        }
        return nullptr;
    }
    
    void Rtp808Service::OnListen(std::shared_ptr<BaseProtocol> client)
    {
        // LOG_DEBUG<<"OnListen:"<<LOG_ENDL;
        auto ptr = std::static_pointer_cast<Rtp808Protocol>(client);
        ptr->SetOnConnection([this](std::shared_ptr<Rtp808Protocol> client)
        {
            // auto oldIter = _connectionClientMap.find(client->getUrl());
            // if (oldIter!=_connectionClientMap.end())
            // {
            //     // client->moveWebSocketList(oldIter->second);
            //     // oldIter->second->Close();
            // }
            // _connectionClientMap.emplace(client->getUrl(), client);
        });
        ptr->SetOnDisconnection([this](std::shared_ptr<Rtp808Protocol> client)
        {
            // LOG_DEBUG<<"remove rtp url:"<<client->getUrl()<<LOG_ENDL;
            // auto iter = _connectionClientMap.find(client->getUrl());
            // if (iter!=_connectionClientMap.end() && iter->second == client)
            // {
            //     _connectionClientMap.erase(iter);
            // }
        });
    }
}
