use strict;
use warnings;
use lib 't';

use TestConnection;
use AnyEvent::XMPP::Ext::VCard;
use MIME::Base64 qw(decode_base64);
use Test::More;

sub test_vcard {
    my ( $username, $expected_fields ) = @_;

    $expected_fields->{'JABBERID'} = $username . '@' . $TestConnection::HOST;
    $expected_fields->{'VERSION'}  = '2.0';

    my $conn  = TestConnection->new($username);
    my $vcard = AnyEvent::XMPP::Ext::VCard->new;

    local $Test::Builder::Level = $Test::Builder::Level + 1;

    $conn->reg_cb(stream_ready => sub {
        $vcard->hook_on($conn);
    });

    $conn->reg_cb(session_ready => sub {
        $vcard->retrieve($conn, undef, sub {
            my ( $jid, $vcard, $error ) = @_;

            if(eval { $vcard->isa('AnyEvent::XMPP::Error') }) {
                $error = $vcard;
            }

            if($error) {
                $conn->cond->send($error->string);
                return;
            }

            delete $vcard->{'_avatar_hash'}; # we don't check this
            delete $vcard->{'PHOTO'};        # PHOTO data is treated specially
                                             # by the vCard extension

            foreach my $key (keys %$vcard) {
                my $value = $vcard->{$key};

                $value = $value->[0] if ref($value) eq 'ARRAY';

                if($value eq '') {
                    delete $vcard->{$key};
                } else {
                    $vcard->{$key} = $value;
                }
            }

            is_deeply $vcard, $expected_fields or diag(explain($vcard));
            $conn->cond->send;
        });
    });

    my $error = $conn->cond->recv;

    if($error) {
        fail($error);
        return;
    }
}

plan tests => 5;

my $photo_data = do {
    local $/;
    my $data = <DATA>;
    chomp $data;

    decode_base64($data)
};

test_vcard(one => {
    FN       => 'John Testerson',
    NICKNAME => 'one',
    TEL      => {
        NUMBER => '555-555-5555',
        WORK   => '',
        VOICE  => '',
    },
});

test_vcard(two => {
    FN       => 'Jane Testerson',
    NICKNAME => 'two',
    TEL      => {
        NUMBER => '',
        WORK   => '',
        VOICE  => '',
    },
});

test_vcard(three => {
    FN       => 'Jerry Testerson',
    NICKNAME => 'three',
    TEL      => {
        NUMBER => '',
        WORK   => '',
        VOICE  => '',
    },
});

test_vcard(four => {
    FN       => 'Jack Testerson',
    NICKNAME => 'four',
    TEL      => {
        NUMBER => '',
        WORK   => '',
        VOICE  => '',
    },
});

test_vcard(five => {
    FN       => 'Jimmy Testerson',
    NICKNAME => 'five',
    TEL      => {
        NUMBER => '',
        WORK   => '',
        VOICE  => '',
    },
    _avatar      => $photo_data,
    _avatar_type => 'image/jpeg',
});

__DATA__
[encoded data, 10472 characters]
9YZB/wABNTJkcEEfWiigpM6rwgyR6vDLJ/q4zvb6Dmiiioe5dj//2Q==
