#!/usr/bin/perl
use warnings;
use strict;

use Mojo::UserAgent;
use Data::Dump qw(dump);

my $ua = Mojo::UserAgent->new;

my $from = 'http://10.60.0.95:5984/drzb2013';
my $to   = 'http://10.60.0.92:5984/drzb2013';

my $docs = $ua->get("$from/_all_docs?include_docs=true")->res->json;

#warn "## docs = ",dump($docs);

foreach my $doc ( map { $_->{doc} } @{ $docs->{rows} } ) {
	warn "OLD ",dump($doc);

	my $new;

	$new->{$_} = delete( $doc->{$_} ) foreach ( qw( _id _rev ) );

	$new->{user} = delete $doc->{person};
	$new->{id}   = delete $doc->{'$id'};

	$new->{user}->{registration_type} = delete $doc->{type};

	$new->{user}->{address}   = delete $new->{user}->{address1};
	$new->{user}->{firstname} = delete $new->{user}->{name};
	$new->{user}->{zip_code}  = delete $new->{user}->{zip};
	$new->{user}->{organization}  = delete $new->{user}->{inst};

	$new->{user}->{dinner}     = delete $doc->{dinner};
	$new->{user}->{hpd_member} = delete $doc->{hpdmember};
	$new->{user}->{student}    = delete $doc->{student};
	$new->{user}->{reception}  = delete $doc->{reception};

	if ( $doc->{r1} eq 'yes' ) {
		$new->{user}->{r1} = {
			required => Mojo::JSON->true,
			OIB     => delete $doc->{r1oib},
			address => delete $doc->{r1address},
			organization => delete $doc->{r1inst},
		};
		warn "need R1";
	}

	if ( $doc->{work}->{title} ) {
		$new->{work}->{$_} = delete $doc->{work}->{$_} foreach (qw( title abstract ));
		$new->{work}->{type} = $new->{user}->{registration_type};
		my @persons = @{ delete $doc->{work}->{authors} };
		foreach my $person ( @persons ) {
			$person->{firstname} = delete $person->{name};
			$person->{organization} = delete $person->{inst};
			push @{ $new->{work}->{persons} }, $person;
		}
	}

	$new->{entity} = 'registration';

	warn "NEW ",dump($new);

	warn "LEFT = ",dump($doc);

	my $id = $new->{_id} || die "no _id in new";
	my $result = $ua->put("$to/$id" => Mojo::JSON->new->encode( $new ))->res->json;

	die "ERROR $id ",dump($result) unless $result->{ok};

	warn "SAVED $id into $to\n";

}

__END__

warn dump(
	$ua->get("$to/_all_docs?include_docs=true")->res->json
);
