package ProjectBuilder::Controller::Conf;
use Mojo::Base 'Mojolicious::Controller';
use Data::Dumper;

sub create { shift->stash(conf => {}) }

sub edit {
  my $self = shift;    # Web request
  $self->stash(conf => $self->confs->find($self->param('id')));
}

sub list {
  my ($self, $args, $cb) = @_;

  if ($cb) {           # Swagger2 request
	  #print "SELF: ".Dumper($self)."\n";
	  #print "ARGS ".Dumper($args)."\n";
	  #print "CB ".Dumper($cb)."\n";
    $self->$cb($self->confs->all, 200);
  }
  else {               # Web request
    $self->render(confs => $self->confs->all);
  }
}

sub remove {
  my ($self, $args, $cb) = @_;

  if ($cb) {           # Swagger2 request
    $self->confs->remove($args->{id});
    $self->$cb({}, 200);
  }
  else {               # Web request
    $self->confs->remove($self->param('id'));
    $self->redirect_to('confs');
  }
}

sub show {
  my ($self, $args, $cb) = @_;

  if ($cb) {           # Swagger2 request
    my $entry = $self->confs->find($args->{id});
    return $self->$cb($entry, 200) if $entry;
    return $self->$cb({errors => [{message => 'ProjectBuilder conf not found.', path => '/id'}]}, 404);
  }
  else {               # Web request
    $self->render(conf => $self->confs->find($self->param('id')));
  }
}

sub store {
  my ($self, $args, $cb) = @_;
  my $validation = $self->_validation($args->{entry});

  if ($cb) {           # Swagger2 request
    $args->{entry}{id} = int $self->confs->add($validation->output);
    return $self->$cb($args->{entry}, 200);
  }
  else {               # Web request
    return $self->render(action => 'create', conf => {}) if $validation->has_error;
    my $id = $self->confs->add($validation->output);
    return $self->redirect_to('show_conf', id => $id);
  }
}

sub update {
  my ($self, $args, $cb) = @_;
  my $validation = $self->_validation($args->{entry});

  if ($cb) {           # Swagger2 request
    $self->confs->save($args->{id}, $validation->output);
    return $self->$cb({}, 200);
  }
  else {               # Web request
    return $self->render(action => 'edit', conf => {}) if $validation->has_error;
    my $id = $self->param('id');
    $self->confs->save($id, $validation->output);
    $self->redirect_to('show_conf', id => $id);
  }
}

sub _validation {
  my ($self, $input) = @_;

  my $validation = $self->validation;
  $validation->input($input) if $input;
  $validation->required('title');
  $validation->required('body');

  return $validation;
}

1;
