#include <stdio.h>
#include "baidu_rtc_client.h"
#define APPID_GET_FROM_BAIDU "appjfkryqbzyns5"
#define BRTC_LOG printf

static void* volatile gBrtcClient = NULL;

static char appid[20] = "";
static char roomname[30] = "2131";
static char userid[20] = "";
static char display[30] = "videocall";
static char token[60] = "no_token";
static char customer_name[60] = "YUHENG";
static int connect_count = 0;

//static char brtcserver[125] = "ws://rtc.exp.bcelive.com:8186/janus";
static char brtcserver[125] = "udp://rtc-ss-udp.exp.bcelive.com:8202";

static const char *ca_info = "-----BEGIN CERTIFICATE-----\r\n\
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\
-----END CERTIFICATE-----";

static void videocall_hangup(void *h);
static void videocall_reconnect(void *h);

static int volatile last_call_time = 0;

#ifndef PRId64
#define PRId64 "lld"
#endif

static void OnRtcMessage(RtcMessage* msg)
{
    BRTC_LOG("OnRtcMessage %d\r\n", msg->msgType);
    switch (msg->msgType)
    {
    case RTC_MESSAGE_ROOM_EVENT_LOGIN_OK:
        {
            break;
        }
    case RTC_MESSAGE_ROOM_EVENT_LOGIN_ERROR:
        {
            if (connect_count > 5) {
                last_call_time = 0;
                brtc_sdk_do_async(videocall_hangup, NULL, 50);
            } else {
                brtc_sdk_do_async(videocall_reconnect, NULL, 50);
            }
            connect_count++;
            break;

        }
    case RTC_MESSAGE_ROOM_EVENT_CONNECTION_LOST:
        {
            brtc_sdk_do_async(videocall_reconnect, NULL, 50);
            break;
        }
    case RTC_MESSAGE_ROOM_EVENT_REMOTE_COMING:
        {
            break;
        }
    case RTC_MESSAGE_ROOM_EVENT_REMOTE_LEAVING:
        {
            break;
        }
    case RTC_ROOM_EVENT_ON_USER_JOINED_ROOM:
        {
            break;
        }
    case RTC_ROOM_EVENT_ON_USER_LEAVING_ROOM:
        {
            brtc_sdk_do_async(videocall_hangup, NULL, 100);
            break;
        }
    case RTC_ROOM_EVENT_ON_USER_MESSAGE:
        {
            //BRTC_LOG("Got User Message id: %" PRId64 ", msg: %s.\n", msg->data.feedId, msg->extra_info);
            break;
        }
    case RTC_MESSAGE_ROOM_EVENT_SERVER_ERROR:
        {
            //BRTC_LOG("ServerEvent error code: %" PRId64 ", reason: %s.\n", msg->data.errorCode, msg->extra_info);
            break;
        }
    case RTC_MESSAGE_STATE_STREAM_UP:
        {
            //²É¼¯³ÌÐò
            printf("RTC_MESSAGE_STATE_STREAM_UP");
            break;
        }
    }
}

static void baidu_init_sdk()
{
    int ret = 0;
    connect_count = 0;
    printf("BRTC: SDK Version %s\n", brtc_sdk_version());
    brtc_sdk_enable_inner_av_devices(1);
    brtc_sdk_enable_nack(0);
    brtc_sdk_enable_log(1);

    ret = brtc_sdk_init();
    if (ret) {
        printf("%s, init failed, ret=%d\n", __func__, ret);
        return ;
    }

    if (gBrtcClient == NULL) {
        gBrtcClient = brtc_create_client();
        BRTC_LOG("create client success\n");
    }

    if (gBrtcClient) {
        brtc_register_message_listener(gBrtcClient, OnRtcMessage);
        brtc_set_cer(gBrtcClient, ca_info);
        brtc_set_server_url(gBrtcClient, brtcserver);
        brtc_set_customer_name(gBrtcClient, customer_name);
        brtc_set_appid(gBrtcClient, appid);

        brtc_set_auto_publish(gBrtcClient, 1);
        brtc_set_auto_subscribe(gBrtcClient, 1);
#if defined(BRTC_USING_G722)
        brtc_set_audiocodec(gBrtcClient, "g722");
#else
        brtc_set_audiocodec(gBrtcClient, "pcmu");
#endif
        brtc_set_usingaudio(gBrtcClient, 1);
        brtc_set_receivingaudio(gBrtcClient, 1);
        brtc_set_usingvideo(gBrtcClient, 0);
        brtc_set_receivingvideo(gBrtcClient, 0);
    }
}

static void baidu_login_room()
{
    int ret = 0;
    if (gBrtcClient) {
        ret = brtc_login_room(gBrtcClient, roomname, userid, display, token);
        if (ret) {
            BRTC_LOG("brtc_login_room success\n");
        } else {
            BRTC_LOG("brtc_login_room failed\n");
        }
    }
}

static void baidu_logout_room()
{
    int ret = 0;
    if (gBrtcClient) {
        ret = brtc_logout_room(gBrtcClient);
        if (ret) {
            BRTC_LOG("logout room success\r\n");
        } else {
            BRTC_LOG("logout room failed\r\n");
        }
    }
}

static void baidu_deinit_sdk()
{
    if (gBrtcClient) {
        brtc_destroy_client(gBrtcClient);
        brtc_sdk_deinit();
        gBrtcClient = NULL;
        printf("destroy success\r\n");
    }
}

static void videocall_hangup(void *h)
{
#ifdef APPID_GET_FROM_BAIDU
    last_call_time = 0;
    baidu_logout_room();
    baidu_deinit_sdk();
#endif
}

static void videocall_reconnect(void *h)
{
    baidu_logout_room();
    brtc_sdk_do_async(baidu_login_room, NULL, 50);
}

void videocall_demo_open(void)
{
    if (last_call_time == 0) {
#ifdef APPID_GET_FROM_BAIDU
        last_call_time = 100;
        strncpy(appid, APPID_GET_FROM_BAIDU, sizeof(appid) - 1);
        sprintf(userid, "600%04d", rand() % 10000);
        baidu_init_sdk();
        baidu_login_room();
#endif
    }
}

void videocall_demo_close(void)
{
    videocall_hangup(NULL);
}

