use strict;

use Medium;

package Medienverwaltung;

my $file_name = "medien.csv";

our $RC_OK     = 0;
our $RC_EXISTS = 1;

sub new {
	my $cn = shift;
	
	my $self = {data => {} };
	bless $self, $cn;
	
	if (-e $file_name) {
		open (my $dh, $file_name);
		while (my $zeile = <$dh>) {
			chomp $zeile;
			my @elems = split (/,/, $zeile);
			die "Invalid file format. 6 elements expected in line: $zeile" unless (scalar @elems == 6);
			$self->anlegen($elems[0],$elems[1],$elems[2],$elems[3],$elems[4],$elems[5]);
		}
	}
	
	return $self;
}

sub anlegen {
	my $self       = shift;
	my $signatur   = shift;
	my $autor      = shift;
	my $titel      = shift;
	my $typ        = shift;
	my $seitenzahl = shift;
	my $spieldauer = shift;
	
	return $RC_EXISTS if (exists $self->{data}->{$signatur});
	
	my $m;
	if ($typ eq "B") {
		$m = new Buch($signatur, $autor, $titel, $seitenzahl);
	} elsif ($typ eq "C") {
		$m = new CD($signatur, $autor, $titel, $spieldauer);
	} else {
		die "Unerwarteter Typ: $typ";
	}
	$self->{data}->{$signatur} = $m;
	
	return $RC_OK;
}

sub lesen {
	my $self = shift;
	my $sign = shift;
	
	return undef unless (exists $self->{data}->{$sign});
	return $self->{data}->{$sign};
}

sub alle_lesen {
	my $self = shift;
	my @marr;
	
	my $data = $self->{data};
	foreach my $sign (keys %$data) {
		push @marr, $data->{$sign};
	}
	return \@marr;
}

sub DESTROY {
	my $self = shift;

	open (my $fh, ">$file_name");
	
	my $data = $self->{data};
	foreach my $sign (keys %$data) {
		print $fh $data->{$sign}->format(), "\n";
	}
	close $fh;
}

1;
