// #define ICARCH_WIN32
// #define ICARCH_IOS_ARM7

#include <PeerSDK.h>
using namespace PeerSDK;

#include <stdio.h>

Peer*       m_peer = NULL;
PeerStream* m_stream = NULL;

int Finalize(int code)
{
    if (m_stream != NULL)
        m_stream->Dispose();

    delete m_peer;

    Peer::Cleanup();
    return code;
}

void PEERSDK_CALLBACK OnErrorOccurred(void* tag, ErrorOccurredEventArgs const& e)
{
    printf("*** error occurred\n");
}

void PEERSDK_CALLBACK OnVideoArrived(void* tag, VideoArrivedEventArgs const& e)
{
    printf("*** video arrived: ");
    switch (e.Type())
    {
    case VideoType_H264_IFrame:
        printf("I-frame  %dx%d\n", e.Width(), e.Height());
        break;
    case VideoType_H264_PFrame:
        printf("P-frame  %dx%d\n", e.Width(), e.Height());
        break;
    default:
        break;
    }
}

void PEERSDK_CALLBACK OnAudioArrived(void* tag, AudioArrivedEventArgs const& e)
{
    printf("*** audio arrived\n");
}

void PEERSDK_CALLBACK OnCompleted(void* tag, CompletedEventArgs const& e)
{
    printf("*** backup complete\n");
}

int main()
{
    PeerResult r;

    r = Peer::Startup();
    if (!r)
    {
        printf("*** failed to initialize\n");
        return Finalize(-1);
    }

    m_peer = new Peer();
    r = m_peer->Connect("192.168.3.38", 80, "Admin", "123456", "", true);
    if (!r)
    {
        printf("*** failed to connect\n");
        return Finalize(-1);
    }

    PeerRecordList* recordList = NULL;
    r = m_peer->CreateRecordList(&recordList);
    if (!r)
    {
        printf("*** failed to get record list\n");
        return Finalize(-1);
    }

    int year  = 2011;
    int month = 12;
    int day   = 23;

    TimeSpanList tsList;
    r = recordList->GetRecordedMinutesOfDay(year, month, day, tsList);
    if (!r)
    {
        printf("*** failed to get record\n");
        return Finalize(-1);
    }

    if (tsList.Count() == 0)
    {
        printf("*** no record segment\n");
        return Finalize(-1);
    }

    r = m_peer->CreateRecordedStream(
        DateTime(year, month, day, tsList[0].Hours(), tsList[0].Minutes(), 0, m_peer),
        DateTime(year, month, day, tsList[0].Hours(), tsList[0].Minutes() + 1, 0, m_peer),
        &m_stream);
    if (!r)
    {
        printf("*** failed to create live stream\n");
        return Finalize(-1);
    }

    m_stream->ErrorOccurred().Add(NULL, OnErrorOccurred);
    m_stream->VideoArrived().Add(NULL, OnVideoArrived);
    m_stream->AudioArrived().Add(NULL, OnAudioArrived);
    m_stream->Completed().Add(NULL, OnCompleted);

    m_stream->SetActive(0);
    m_stream->SetChannelMask(0xFFFF, 0xFFFF);
    m_stream->Start();

    while (true)
    {
        char c = 0;
        scanf("%c", &c);
        if (c == 'q')
            break;
    }

    return Finalize(0);
}
