package myHive::Model::Area::Manager;
use Moose;
use MooseX::Params::Validate;
use namespace::autoclean;
use TryCatch;
use myHive::Model::DB;
use myHive::Model::Area;
use Data::Dumper;

extends 'Catalyst::Model';

=head1 NAME

myHive::Model::Area - Catalyst Model

=head1 DESCRIPTION

Catalyst Model.

=head1 AUTHOR

root

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

has 'handler' 	=> ( is => 'ro', isa => 'myHive::Model::DB::Areas', default => sub { myHive::Model::DB::Areas->new } );
has 'collection' => ( is => 'rw', isa => 'ArrayRef', default => sub { [] } );


sub add {
	try {
		my ( $self, %params ) = validated_hash(
                         \@_,
                        account         => { isa => 'Str' },
                        area_name       => { isa => 'Str' },
			id              => { isa => 'Str', optional => 1 },

                );
                $params{name} = $params{area_name};
                delete $params{area_name};
		$params{log} = 1;
		my $sth = $self->handler->add( %params );
                my $row = $sth->fetchrow_hashref;
		$row->{addareas} =~ s{\A \( | \) \z}{}xgm;
		my @addAreasElement = split(',', $row->{addareas});
                print STDERR Dumper($row);
		print STDERR Dumper(\@addAreasElement);
                return (1, \@addAreasElement );

		


	}
	catch($e) {
		print STDERR "area->add failed: ". $e;
                return;

	}
	return;

}

sub getArea {
	my ( $self, %params ) = @_;
	my $sth = $self->handler->selectSTH(
				table => ['areas'],
				fields => ['*'],
				where  => qq/id = $params{id}/,
		 );
	my $row = $sth->fetchrow_hashref;
	$sth->finish;	
	return myHive::Model::Area->new(
                                id              => $row->{id},
                                account         => $row->{account},
                                name            => $row->{name},

                        );


}

sub getAreas {
	my ( $self , %params ) = @_;
	my $sth = $self->handler->selectSTH(
				table  => ['areas'],
				fields => ['*'],
				where  => qq/account = $params{account}/,
		);
	while ( my $row = $sth->fetchrow_hashref ) {
		my $area = myHive::Model::Area->new(
                                id              => $row->{id},
                                account         => $row->{account},
                                name            => $row->{name},

                        );

		push ( @{ $self->collection }, $area ); 

	}
	$sth->finish;
	return $self->collection;

}

sub updateArea {
	my ( $self, %params ) = @_;
	$self->handler->update(
			table	=> ['areas'],
			data    => { name => $params{name} },
			where	=> qq/id  = $params{id} /,
	);

	return;
}

__PACKAGE__->meta->make_immutable;

1;
