package Gantry::Samples::FileUpload;

use strict;

use base 'Gantry::Samples';

#-----------------------------------------------------------------
# $self->do_main(  )
#-----------------------------------------------------------------
sub do_main {
    my ( $self ) = @_;

    $self->stash->view->title( 'File Upload' );
    $self->template( 'fileupload.tt' );

    if ( my @errors = $self->checkvals ) {

        # pass the errors to the template if posting
        if ( $self->is_post ) {
            $self->stash->view->data( { errors => \@errors } );
        }
    }
    else {

        # get the upload information
        my $upload = $self->file_upload( 'file' );

        # build a unique filename
        my $file = (
            $upload->{unique_key}
            . $upload->{name}
            . $upload->{suffix}
        );

        # open your file for write
        open( FH, '>' . $self->doc_root() . "/$file" ) or die $!;
        binmode FH;

        # ... and write the file
        my( $buffer, $buffer_size ) = ( '', 4096 );
        while ( read( $upload->{filehandle}, $buffer, $buffer_size ) ) {
            print FH $buffer;
        }
        close FH;

        $self->stash->view->data ( {
            uploaded_file => $upload,
            uploaded_file_location => $file,
        } );
    }

} # END do_main

sub checkvals {
    my $self = shift;

    my %p = $self->get_param_hash();

    my @errors;
    push( @errors, 'File Required' ) unless $p{file};

    return( @errors );

}

1;

=head1 NAME

Gantry::Samples::FileUpload - A controller in the Gantry::Samples application

=head1 SYNOPSIS

This package is meant to be used in a stand alone server/CGI script or the
Perl block of an httpd.conf file.

Stand Alone Server or CGI script:

    use Gantry::Samples::FileUpload;

    my $cgi = Gantry::Engine::CGI->new( {
        config => {
            #...
        },
        locations => {
            '/someurl' => 'Gantry::Samples::FileUpload',
            #...
        },
    } );

httpd.conf:

    <Perl>
        # ...
        use Gantry::Samples::FileUpload;
    </Perl>

    <Location /someurl>
        SetHandler  perl-script
        PerlHandler Gantry::Samples::FileUpload
    </Location>

If all went well, one of these was correctly written during app generation.

=head1 DESCRIPTION

This module was originally generated by Bigtop.  But feel free to edit it.
You might even want to describe the table this module controls here.

=head1 METHODS

=over 4

=item do_main

=item schema_base_class

=item get_orm_helper


=back


=head1 DEPENDENCIES

    Gantry::Samples

=head1 AUTHOR

Timotheus Keefer, E<lt>tkeefer@apple.comE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2006 Timotheus Keefer

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.6 or,
at your option, any later version of Perl 5 you may have available.

=cut
