/**
 * Writes the profile image of a contact to disk so ActionScript can load it when needed.
 */
bbmsp_result_t saveContactAvatar( bbmsp_contact_t* contact, char *path )
{
	bbmsp_result_t result;
	char *ppid;
	result = contact_get_property( contact, &ppid, bbmsp_contact_get_ppid, BBMSP_CONTACT_PPID_MAX );

	if( result == BBMSP_SUCCESS )
	{

		bbmsp_image_t* m_contact_avatar;
		bbmsp_image_create_empty( &m_contact_avatar );
		result = bbmsp_contact_get_display_picture( contact, m_contact_avatar );

		if( result == BBMSP_SUCCESS )
		{

			getAvatarPath( m_contact_avatar, ppid, path );
			saveFile( path, m_contact_avatar );
		}
		else
		{
			trace( "saveContactAvatar picture %i", result );
		}

		bbmsp_image_destroy( &m_contact_avatar );

	}
	else
	{
		trace( "saveContactAvatar ppid %i", result );
	}

	return( result );
}
void BBMBPS::SetDisplayPicture(const std::string& imgPath)
{
    MUTEX_LOCK();
    std::string fileType = imgPath.substr(imgPath.find_last_of(".") + 1, imgPath.length());
    bbmsp_image_type_t type;

    if (fileType == "jpg" || fileType == "jpeg") {
        type = BBMSP_IMAGE_TYPE_JPG;
    } else if (fileType == "png") {
        type = BBMSP_IMAGE_TYPE_PNG;
    } else if (fileType == "gif") {
        type = BBMSP_IMAGE_TYPE_GIF;
    } else if (fileType == "bmp") {
        type = BBMSP_IMAGE_TYPE_BMP;
    } else {
        //unsupported format
        return;
    }

    bbmsp_image_t *avatar;
    int img = 0;
    int size = 0;
    struct stat fstats;
    char *imgData;

    img = open(imgPath.c_str(), O_RDONLY);

    if (img != -1) {
        fstat(img, &fstats);
        size = fstats.st_size;
        imgData = new char[size];
        size = read(img, imgData, size);
        if (size) {
            bbmsp_image_create(&avatar, type, imgData, size);
            bbmsp_set_user_profile_display_picture(avatar);
            bbmsp_image_destroy(&avatar);
        }
        delete imgData;
        close(img);
    }
    MUTEX_UNLOCK();
}
int BBMBPS::WaitForEvents()
{
    MUTEX_LOCK();
    int status = bbmsp_request_events(0);

    bps_event_t *event = NULL;
    bbmsp_event_t *bbmEvent;
    bbmsp_profile_t *bbmProfile;

    for (;;) {
        MUTEX_UNLOCK();
        bps_get_event(&event, -1);
        MUTEX_LOCK();
        if (event) {
            int event_domain = bps_event_get_domain(event);

            if (event_domain == bbmsp_get_domain()) {
                int eventCategory = 0;
                int eventType = 0;

                bbmsp_event_get(event, &bbmEvent);

                if (bbmsp_event_get_category(event, &eventCategory) == BBMSP_SUCCESS) {
                    switch (eventCategory) {
                        case BBMSP_REGISTRATION:
                        {
                            if (bbmsp_event_get_type(event, &eventType) == BBMSP_SUCCESS) {
                                switch (eventType) {
                                    case BBMSP_SP_EVENT_ACCESS_CHANGED:
                                        processAccessCode(bbmsp_event_access_changed_get_access_error_code(bbmEvent));
                                        break;
                                }
                            }
                            break;
                        }
                        case BBMSP_USER_PROFILE:
                        {
                            if (bbmsp_event_get_type(event, &eventType) == BBMSP_SUCCESS) {
                                switch (eventType) {
                                    case BBMSP_SP_EVENT_PROFILE_CHANGED:
                                    {
                                        bbmsp_presence_update_types_t profileUpdateType;
                                        bbmsp_event_profile_changed_get_profile(bbmEvent, &bbmProfile);
                                        if (bbmsp_event_profile_changed_get_presence_update_type(bbmEvent, &profileUpdateType) == BBMSP_SUCCESS) {
                                            if (profileUpdateType == BBMSP_DISPLAY_PICTURE) {
                                                bbmsp_image_t *avatar;
                                                char *imgData = NULL;
                                                char *output = NULL;

                                                bbmsp_image_create_empty(&avatar);
                                                if (bbmsp_profile_get_display_picture(bbmProfile, avatar) == BBMSP_SUCCESS) {
                                                    imgData = bbmsp_image_get_data(avatar);

                                                    int size = bbmsp_image_get_data_size(avatar);
                                                    output = new char[size*4];

                                                    int bufferSize = b64_ntop(reinterpret_cast<unsigned char *>(imgData), bbmsp_image_get_data_size(avatar), output, size*4);
                                                    output[bufferSize] = 0;
                                                    m_pParent->NotifyEvent(std::string("self.getDisplayPicture ").append(output));
                                                    delete output;
                                                }
                                                bbmsp_image_destroy(&avatar);
                                            } else {
                                                processProfileUpdate(bbmEvent);
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                        case BBMSP_CONTACT_LIST:
                        {
                            if (bbmsp_event_get_type(event, &eventType) == BBMSP_SUCCESS) {
                                switch (eventType) {
                                    case BBMSP_SP_EVENT_CONTACT_CHANGED:
                                    {
                                        processContactUpdate(bbmEvent);
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (event_domain == m_BBMInternalDomain) {
                int code = bps_event_get_code(event);
                if (code == INTERNAL_EVENT_REGISTER) {
                    bps_event_payload_t *payload = bps_event_get_payload(event);
                    char *uuid = reinterpret_cast<char *>(payload->data1);
                    bbmsp_register(uuid);
                    delete uuid;
                } else if (code == INTERNAL_EVENT_CONTACT_EVENTS) {
                    bbmsp_event_contact_list_register_event();
                    contactEventsEnabled = true;
                } else if (code == INTERNAL_EVENT_STOP) {
                    break;
                }
            }
        }
    }
    return (status == BPS_SUCCESS) ? 0 : 1;
}
/**
 * Creates a ActionScript net.rim.bbm.BBMContact instance from the supplied native contact.
 */
FREObject createActionScriptContact( const bbmsp_contact_t* contact )
{
	FREObject contact_AS = NULL;

	const int cNumAttributes = 7;
	FREObject resultAttributes[cNumAttributes];

	bbmsp_result_t result;

	char ppid[BBMSP_CONTACT_PPID_MAX];
	result = bbmsp_contact_get_ppid( contact, ppid, BBMSP_CONTACT_PPID_MAX );

	if( result == BBMSP_SUCCESS )
	{
		FRENewObjectFromUTF8((uint32_t)(strlen(ppid) + 1), (uint8_t*)ppid, &resultAttributes[0]);
	}
	else
	{
		trace( "createActionScriptContact ppid %i", result );
	}


	char displayName[BBMSP_CONTACT_DISPLAY_NAME_MAX];
	result = bbmsp_contact_get_display_name( contact, displayName, BBMSP_CONTACT_DISPLAY_NAME_MAX );
	if( result == BBMSP_SUCCESS )
	{
		FRENewObjectFromUTF8((uint32_t)(strlen(displayName) + 1), (uint8_t*)displayName, &resultAttributes[1]);
	}
	else
	{
		trace( "createActionScriptContact displayName %i", result );
	}


	char personalMessage[BBMSP_CONTACT_PERSONAL_MSG_MAX];
	result = bbmsp_contact_get_personal_message( contact, personalMessage, BBMSP_CONTACT_PERSONAL_MSG_MAX );
	if( result == BBMSP_SUCCESS )
	{
		FRENewObjectFromUTF8((uint32_t)(strlen(personalMessage) + 1), (uint8_t*)personalMessage, &resultAttributes[2]);
	}
	else
	{
		trace( "createActionScriptContact personalMessage %i", result );
	}

	char statusMessage[BBMSP_CONTACT_STATUS_MSG_MAX];
	result = bbmsp_contact_get_status_message( contact, statusMessage, BBMSP_CONTACT_STATUS_MSG_MAX );
	if( result == BBMSP_SUCCESS )
	{
		FRENewObjectFromUTF8((uint32_t)(strlen(statusMessage) + 1), (uint8_t*)statusMessage, &resultAttributes[3]);
	}
	else
	{
		trace( "createActionScriptContact statusMessage %i", result );
	}

	char appVersion[BBMSP_CONTACT_APP_VERSION_MAX];
	result = bbmsp_contact_get_app_version( contact, appVersion, BBMSP_CONTACT_APP_VERSION_MAX );
	if( result == BBMSP_SUCCESS )
	{
		FRENewObjectFromUTF8((uint32_t)(strlen(appVersion) + 1), (uint8_t*)appVersion, &resultAttributes[4]);
	}
	else
	{
		trace( "createActionScriptContact appVersion %i", result );
	}

	bbmsp_presence_status_t status;
	result = bbmsp_contact_get_status( contact, &status );
	if( result == BBMSP_SUCCESS )
	{
		FRENewObjectFromInt32( (int32_t)status, &resultAttributes[5]);
	}
	else
	{
		trace( "createActionScriptContact status %i", result );
	}


	bbmsp_image_t* m_contact_avatar;
	bbmsp_image_create_empty(&m_contact_avatar);

	result = bbmsp_contact_get_display_picture( contact, m_contact_avatar );
	trace( "%i picture", result );

	if( result == BBMSP_SUCCESS )
	{
		char path[PATH_MAX];
		getAvatarPath( m_contact_avatar, ppid, path );
		FRENewObjectFromUTF8((uint32_t)(strlen(path) + 1), (uint8_t*)path, &resultAttributes[6]);
	}
	else
	{
		resultAttributes[5] = NULL;
	}

	bbmsp_image_destroy( &m_contact_avatar );

	FRENewObject((const uint8_t*) "Array", cNumAttributes, resultAttributes, &contact_AS, NULL);

	return( contact_AS );
}