package myHive::Controller::API;
use Moose;
use namespace::autoclean;
use Data::Dumper;
BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

myHive::Controller::API - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

sub begin : Private {
        my ( $self, $c ) = @_;

        #$c->config->{session}->{'Catalyst::Plugin::Session'} = 'bug';#horrible
        $c->{authentication}    = myHive::Model::Authentication->new;
        $c->{landowner}         = myHive::Model::Landowner::Manager->new;
        $c->{area}              = myHive::Model::Area::Manager->new;
	$c->{sites}		= myHive::Model::Site::Manager->new;
	$c->{landowners}	= myHive::Model::Landowner::Manager->new;
	$c->{broodtype}		= myHive::Model::BroodType::Manager->new;

        return;
}





=head2 index

=cut

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    $c->response->body('Matched myHive::Controller::API in API.');
}

sub authenticate : Local : Args() { 
        my ( $self, $c ) = @_; 
	my $mafref    = $c->request->query_parameters->{mafref};
        my $username = $c->request->query_parameters->{username};
        my $password = $c->request->query_parameters->{password};
	if ( exists $c->session->{seed} && $c->session->{mafref} != $mafref ) {
		my $account_id = $c->{authentication}->checkUserCredentials(
                                        username => $username,
                                        password => $password,
					mafref   => $mafref,
                                );
		
		if ( $account_id )  {
                        $c->session(
                                {
                                        loggedin        => 'yes',
                                        username        =>  $username,
                                        mafred          =>  $mafref,
                                        account_id      =>  $account_id,
                                        seed            =>  $c->generate_session_id,
                                        expires         =>  5
                                }
                        );
                }

	}  
        
        if ( !exists  $c->session->{account_id} ) {
                 my $account_id = $c->{authentication}->checkUserCredentials(
                                        username => $username,
                                        password => $password,
					mafref   => $mafref,
                                );
                 print STDERR "account id: $account_id";
                 if ( $account_id )  {
                        $c->session(
                                {
                                        loggedin        => 'yes',
                                        username        =>  $username,
					mafred		=>  $mafref,
                                        account_id      =>  $account_id,
                                        seed            =>  $c->generate_session_id,
                                        expires         =>  5
                                }
                        );
                }


        }

        $c->stash->{seed} =  $c->session->{seed} || 'failed';
        $c->stash->{template} = 'rest/json_authentication.tt';
        return;
}

sub checkseed : Private {

	my ( $self , $c, $seed ) = @_;
	print STDERR "checkSeed called";
	print STDERR Dumper($c->session);
	if ( $seed eq $c->session->{seed} ) {
		return 1;
	}
	else {
		return 0;
	}
	return 0;
}



sub getAreas : Local : Args(1) {
        my ( $self, $c,$seed ) = @_;
        if ( $seed eq $c->session->{seed} ) {
                $c->stash->{areas} = $c->{area}->getAreas( account => $c->session->{account_id} );
        }
        $c->stash->{template} = 'rest/areas.tt';
        return;
}

sub getSites : Local : Args(1) {
	my ( $self, $c,$seed ) = @_;
        if ( $seed eq $c->session->{seed} ) {
		print STDERR Dumper($c->session);
                $c->stash->{sites} = $c->{sites}->getSites( account => $c->session->{account_id} );
        }
        $c->stash->{template} = 'rest/sites.tt';
        return;

	

}

sub getLandowners : Local : Args(1) {
	my ( $self, $c, $seed ) = @_;
	if ( $seed eq $c->session->{seed} ) {
                print STDERR Dumper($c->session);
                $c->stash->{landowners} = $c->{landowners}->getLandowners( account => $c->session->{account_id} );
        }
        $c->stash->{template} = 'rest/landowners.tt';
        return;


}

sub getBroodTypes : Local : Args() {
	my ( $self, $c , $seed ) = @_;
	if ( $seed eq $c->session->{seed} ) {
                print STDERR Dumper($c->session);
                $c->stash->{broodtypes} = $c->{broodtype}->getBroodTypes( account => $c->session->{account_id} );
        }
        $c->stash->{template} = 'rest/broodtypes.tt';
        return;


}

sub getInepection : Local : Args() {
	my ( $self, $c, $seed ) = @_;
	$c->stash->{template} = 'rest/inspection.tt';
}

sub addInspection : Local : Args() {
	my ( $self, $c, $data ) = @_;
	
	$c->stash->{template} = 'rest/addinspection.tt';

}


sub updateSites : Local : Args() {
	my ( $self, $c, $seed, $JSON ) = @_;
	 print STDERR "update  Site JSON: " . Dumper($JSON);
	 if ( $seed eq $c->session->{seed} ) {
		my %params;
		my $data = $c->request->body_parameters;
		$params{broodtypes} = '{}';
		$params{account}    = $c->session->{account_id};
		$params{site_id}    = $data->{siteID};
		$params{site_name}  = $data->{siteName} || '';
		$params{area}       = $data->{siteArea};
		$params{landowner}  = $data->{siteLandowner};
		$params{maf_ref}    = $data->{siteMafRef} || '';
		$params{descr}      = $data->{siteDesc}   || '';
		$params{latlng}     = $data->{siteLatLng} || '';		
		print STDERR "params " . Dumper(\%params);
		#my $status = $c->{sites}->update( %params );
		$c->{manager}  = myHive::Model::Site::Manager->new(  account => $c->session->{account_id} );
		my $status = $c->{manager}->update( %params );
		if ( $status) {
			$c->stash->{updated} = 'Y';
		}
		else {
			$c->stash->{updated} = 'N';	
		}
		 #print STDERR "update Sites Data: " . Dumper($c->request->body_parameters);
	}
	$c->stash->{template} = 'rest/updatesites.tt';

	return;

}

sub addSiteSchedule : Local : Args() {
	my ( $self, $c, $seed ) = @_;
	 if ( $seed eq $c->session->{seed} ) {
                my %params;
                my $data = $c->request->body_parameters;
		$params{account}    		= $c->session->{account_id};
		$params{siteId}    		= $data->{scheduleSiteID};
		$params{date}    		= $data->{scheduleDate};
		$params{reason}    		= $data->{scheduleReason};
		$params{additionalInfo}  	= $data->{scheduleAdditionalInfo} || 'nothing';
		$c->{manager}       		= myHive::Model::Site::Manager->new(  account => $c->session->{account_id} );
		my ($status , $scheduleId )  	= $c->{manager}->addSchedule( %params );
		if ( $status) {
                        $c->stash->{updated} = 'Y';
			$c->stash->{scheduleId} = $scheduleId;
                }
                else {
                        $c->stash->{updated} = 'N';
                }
	
	}
	else {
		$c->stash->{updated} = 'N';
	}
	$c->stash->{template} = 'rest/addschedule.tt';
	return;
}


=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

__PACKAGE__->meta->make_immutable;

1;
