package SmokeOrNot::Controller::Cities;

use strict;
use warnings;
use parent 'Catalyst::Controller::HTML::FormFu';

=head1 NAME

SmokeOrNot::Controller::Cities - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 index 

=cut

#sub index :Path :Args(0) {
sub index : PathPart('cities') Chained('/language') Args(0) {
    my ( $self, $c ) = @_;

    #$c->response->body('Matched SmokeOrNot::Controller::Cities in Cities.');
    $c->response->redirect( $c->uri_for('create') );
    $c->detach();
}

=head2 create

Use HTML::FormFu to create a new city

=cut

#sub create :Local :FormConfig {
sub create : PathPart('cities/create') Chained('/language') Args(0)
    : FormConfig {
    my ( $self, $c, $id ) = @_;

    # Get the form that the :FormConfig attribute saved in the stash
    my $form = $c->stash->{form};

    # Clear the flash
    $c->clear_flash();

    if ( $form->submitted_and_valid ) {

        my $city = $c->model('DB::City')->new_result( {} );

        # Save the form data for the bar
        $form->model->update($city);

        # Set a status message for the user
        $c->flash->{status_msg}
            = $c->loc('City ') . $city->name . $c->loc(' created');

        # Return to the bar list
        $c->response->redirect( $c->uri_for('../bars/create_edit') );
        $c->detach();

    } else {

        # Get the countries from the DB
        my @countryObjs = $c->model("DB::Country")->all();

        # Create an array of arrayrefs where each arrayref is a city
        my @countries;
        foreach ( sort { $a->name cmp $b->name } @countryObjs ) {
            push( @countries, [ $_->id, $_->name ] );
        }

        # Get the select added by the config file
        my $select_country = $form->get_all_element( { name => 'country' } );

        # Add the cities to it
        $select_country->options( \@countries );

    }

    # Set the template
    $c->stash->{template} = 'cities/create.tt2';
}

=head1 COPYRIGHT

Copyright 2009-2010, gregor herrmann <gregor.herrmann@comodo.priv.at>

=head1 LICENSE

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

=cut

1;
