/************************************************************
* Details: 网关，负责本地网络请求数据中转
* Encode: UTF-8
* Platform: Android & Linux
* Author: R&D 2
* Date: 2018-4-2
************************************************************/
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <time.h>
#include "gterror.h"
#include "gt.h"
#include "gttoolkitext.h"
#include "gtmessageloop.h"
#include "gtnetworkloop.h"
#include "gtgateway.h"

GtGateway *GtGateway::_instance = NULL;

GtGateway::GtGateway()
{

}

GtGateway::~GtGateway()
{

}

GtGateway *GtGateway::instance()
{
    if(_instance == NULL)
    {
        _instance = new GtGateway();
    }
    return _instance;
}

void *GtGateway::messageEntry(void *obj)
{
    if(obj == NULL)
    {
        return NULL;
    }
    GtGateway *threadObj = (GtGateway *)obj;
    if(threadObj == NULL)
    {
        return NULL;
    }
    threadObj->messageLoop();
    return threadObj;
}

void *GtGateway::networkEntry(void *obj)
{
    if(obj == NULL)
    {
        return NULL;
    }
    GtGateway *threadObj = (GtGateway *)obj;
    if(threadObj == NULL)
    {
        return NULL;
    }
    threadObj->networkLoop();
    return threadObj;
}

void GtGateway::networkLoop()
{
    GtNetworkLoop::instance()->loop();
}

void GtGateway::messageLoop()
{
    GtMessageLoop::instance()->loop();
}

void GtGateway::start()
{
    pthread_t thread;
    int result = 0;

    //初始化消息队列
    if(!GtMessageLoop::instance()->initMessage(5))
    {
        exit(-1);
    }
    result = pthread_create(&thread, NULL, messageEntry, (void *)this);
    if(result != 0)
    {
        GtToolkitExt::logError(__FILE__, __LINE__, "创建消息Loop错误");
        exit(-1);
    }
    //初始化网络
    if(!GtNetworkLoop::instance()->initNetwork(10))
    {
        exit(-1);
        return;
    }
    result = pthread_create(&thread, NULL, networkEntry, (void *)this);
    if(result != 0)
    {
        GtToolkitExt::logError(__FILE__, __LINE__, "创建网络Loop错误");
        exit(-1);
        return;
    }
}

void GtGateway::stop()
{
    GtMessageLoop::instance()->stop();
    GtNetworkLoop::instance()->stop();
}
