#!/usr/bin/perl -w

use CORBA::MICO ids => [ 'IDL:Account/Account:1.0' => undef,
			 'IDL:Account/AcctCounter:1.0' => undef ];

package MyCounter;

@MyCounter::ISA = qw(Account::AcctCounter);

my %counters = ();

sub new {
    my $count = 0;
    my $self = bless \$count;
    $counters{$self} = $self;

    $self;
}

sub next {
    my $self = shift;
    return (++$$self);
}

sub destroy {
    my $self = shift;
    delete $counters{$self};
}

package MyAccount;

@MyAccount::ISA = qw(Account::Account);

sub new {
    my ($class) = @_;
    my $self = bless {}, $class;
      
    $self->{current_balance} = 0;
    $self->{prefs} = {
		      favorite_color => 'burgundy',
		      lottery_numbers => [ 1, 2, 3, 4]
		     };

    $self;
}

sub set_pref {
    my $self = shift;
    my ($d, $v) = @{shift()};

    if ($d eq "pt_color") {
	$self->{prefs}->{favorite_color} = $v;
    } elsif ($d eq "pt_lotnum") {
	$self->{prefs}->{lottery_numbers} = $v;
    }
}

sub get_pref {
    my ($self,$d) = @_;

    if ($d eq "pt_color") {
	return [$d, $self->{prefs}->{favorite_color}];
    } elsif ($d eq "pt_lotnum") {
	return [$d, $self->{prefs}->{lottery_numbers}];
    }
}

sub get_pref_any {
    my ($self,$d) = @_;

    if ($d eq "pt_color") {
	return new CORBA::Any (CORBA::TypeCode->new('IDL:Account/Account/Color:1.0'),
			       $self->{prefs}->{favorite_color});
    } elsif ($d eq "pt_lotnum") {
	return new CORBA::Any (CORBA::TypeCode->new('IDL:Account/Account/numbers:1.0'),
			       $self->{prefs}->{lottery_numbers});
    }
}

sub deposit {
    my ($self,$amount) = @_;
    $self->{current_balance} += $amount;
}

sub withdraw {
    my ($self,$amount) = @_;
    if ($amount > $self->{current_balance}) {
	throw Account::Account::InsufficientFunds
	    overdraft => $amount - $self->{current_balance};
    } else {
	$self->{current_balance} -= $amount;
    }
}

sub balance { 
    $_[0]->{current_balance} 
};

sub counter {
    return new MyCounter;
}

# Possible alternative mapping
#
#sub prefs {
#    ($self, $val) = @_;
#    defined $val || return $self->{prefs};
#    $self->{prefs} = $val;
#}

sub _get_prefs { 
    $_[0]->{prefs}; 
}

sub _set_prefs {
    my ($self,$p) = @_;
    $self->{prefs} = $p;
}

package main;

$orb = CORBA::ORB_init("mico-local-orb");
$boa = $orb->BOA_init("mico-local-boa");

$server = new MyAccount;
$ref = $orb->object_to_string ($server);

open (OUT, ">account.ref");
print OUT "$ref";
close OUT;

$boa->impl_is_ready ( undef );
