package SmokeOrNot::Controller::Root;

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

#
# Sets the actions in this controller to be registered with no prefix
# so they function identically to actions created in MyApp.pm
#
__PACKAGE__->config->{namespace} = '';

=head1 NAME

SmokeOrNot::Controller::Root - Root Controller for SmokeOrNot

=head1 DESCRIPTION

[enter your description here]

=head1 METHODS

=cut

=head2 index

=cut

#sub index :Path :Args(0) {
sub index : PathPart('') Chained('/language') Args(0) {

    my ( $self, $c ) = @_;

    # Hello World
    #$c->response->body( $c->welcome_message );

    # site/index
    $c->response->redirect( $c->uri_for( $c->language, 'site' ) );
    $c->detach();
}

=head2 default

=cut 

sub default : Path {
    my ( $self, $c ) = @_;
    $c->response->body('Page not found');
    $c->response->status(404);
}

=head2 begin

=cut

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

    my $oldpath = $c->req->path;
    ( my $newpath = $oldpath ) =~ s;/index/?$;;;

    if ( $oldpath ne $newpath ) {
        $c->response->redirect( $c->uri_for("/$newpath") );
        $c->detach();
    }

    if ( $oldpath eq '' ) {
        $c->detach('index');
    }

    $newpath =~ s;%2F;/;;
    $newpath =~ s;//;/;g;
    $c->req->path($newpath);

    if ( $c->req->match eq '/' && $c->req->method eq 'GET' ) {
        $c->forward('language');
        $c->forward($newpath);
        if ( $c->error ) {
            $newpath = $c->language . "/$newpath";
            $c->response->redirect( $c->uri_for($newpath) );
        }
        $c->detach();
    }
}

=head2 language

=cut

sub language : PathPart('') Chained('/') CaptureArgs(1) {
    my ( $self, $c, $language ) = @_;
    my %allowed_languages = map { $_ => 1 } ( 'en', 'de' );

    # $c->languages already contains the languages from
    # $c->request->header('Accept-Language'), thanks to Catalyst::Plugin::I18N
    if ( $language and $allowed_languages{$language} ) {
        $c->languages( [$language] );
    }
}

=head2 end

Attempt to render a view, if needed.

=cut 

sub end : ActionClass('RenderView') {
}

=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;
