package LATMOS::Accounts::Web::Controller::NetHosts;

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

=head1 NAME

LATMOS::Accounts::Web::Controller::Users - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

sub index : Private {
    my ( $self, $c ) = @_;
    
    $c->stash->{ofilter} = $c->model('AttrFilter', 'nethost');
    my $start = $c->req->param('start');
}

sub default : LocalPath {
    my ( $self, $c, undef, $nethostname ) = @_;

    my $base = $c->model('Accounts')->db;
    $c->stash->{page}{title} = "Hôte réseau :: $nethostname";
    $c->stash->{nethost} = $base->get_object('nethost', $nethostname) or do {
        $c->forward('/no_object');
        return;
    };
    $c->stash->{nethostname} = $nethostname;
    $c->stash->{form} = $c->model('AttrForms', 'nethost', $c->stash->{nethost});
    if ($c->req->param('addip')) {
        for (1) {
            my $zone = $base->get_object('netzone', $c->req->param('zone'))
                or last;
            my $ip = $c->req->param('newip') || 'any';
            if ($ip =~ /^(any|first)$/) {
                my @freeips = $zone->get_attributes('freeIP') or last;
                my $idx = $ip eq 'first' ? 0 : rand(scalar(@freeips));
                $ip = $freeips[$idx] or last;
            }
            my @currentips = grep { $_ } $c->stash->{nethost}->get_attributes('ip');
            $c->stash->{nethost}->set_c_fields(ip => [ @currentips, $ip ])
                or do {
                $base->rollback;
                last;
            };
            $base->commit;
            last;
        }
    } elsif ($c->req->param('rename') && $c->req->param('to')) {
        my $to = $c->req->param('to');
        if ($base->rename_nethost($nethostname, $to,
            addcname => $c->req->param('addcname') || undef,
        )) {
            $base->commit;
            $c->res->redirect($to);
        } else {
            $base->rollback;
        }
    } elsif ($c->req->param('make_active')) {
        $c->stash->{nethost}->set_c_fields('exported' => 1);
        $base->commit;
    }
    elsif ($c->req->param('make_inactive')) {
        $c->stash->{nethost}->set_c_fields('exported' => 0);
        $base->commit;
    }
    elsif ($c->req->param('delete')) {
        $base->delete_object('nethost', $nethostname);
        $base->commit;
        $c->res->redirect('/nethosts');

    } else {
        $c->stash->{form}->set_attrs;
    }
}

=head1 AUTHOR

Thauvin Olivier

=head1 LICENSE

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

=cut

1;
