package Platform::DBI;
use base 'Local::Class::DBI';
use Class::DBI::AbstractSearch;
use Local::Class::DBI::Plugin::DeepAbstractSearch;
use Local::HTML::FieldForm;
use strict;
use warnings;

sub connection {
  my ($self, $data_source, $user, $password, $attr) = @_;

  $attr->{'pg_enable_utf8'} = 1;

  $self->SUPER::connection($data_source, $user, $password, $attr);
}

sub uri {
  my ($self, $subsection) = @_;

  return join('/', grep { defined } '', $self->moniker, $subsection, $self . '.html');
}

sub field_form {
  my ($proto) = shift;
  if (ref $proto) { # we have an object
    my $form = Local::HTML::FieldForm->new(%{$proto->Field_form});
    my @copy_fields = grep !$form->{$_}{nocopy}, keys %{$form};
    my %values;
    @values{@copy_fields} = map { my $foo = $proto; map { $foo = $foo->$_ if (defined $foo) } split(/\./, $_); defined $foo && ($foo ne '') ? "$foo" : undef } @copy_fields;
    $form->set_values(\%values);
    return $form;
  } else {
    return  Local::HTML::FieldForm->new(%{$proto->Field_form});
  }
}

sub create_from_form {
  my ($class,$form) = @_;
  my %form_data = $form->get_values;

  for my $key (keys %form_data) {
    delete $form_data{$key} if $form->{$key}{nocopy};
  }

  return $class->create(\%form_data);
}

sub save_from_form {
  my ($object, $form) =  @_;
  my %form_data = $form->get_values;

  my %children;
  for my $key (keys %form_data) {
    if ($form->{$key}{nocopy}) {
      next;
    }

    my @methods = split(/\./, $key);

    my $foo = $object;
    while ($#methods > 0) {
      my $method = shift @methods;
      $foo = $foo->$method;
    }

    my $method = shift @methods;
    $foo->$method($form_data{$key});

    $children{$foo} = $foo;
  }

  map { $_->update; } values %children;
}

sub check_missing {
  my ($self, %args) = @_;

  my $missing;
  no strict "refs";
  foreach my $field (@{(ref($self) || $self) . '::required_fields'}) {
    unless ($args{$field} =~ /\w/) {
      push @{$missing}, $field;
    }
  }

  return $missing;
}

sub set_many {
  my ($self, $many, $field, $value) = @_;

  $value = [ $value ] unless (ref($value) eq 'ARRAY');

  my %value_hash = ( map { $_ => 1 } @{$value} );

  foreach my $item ($self->$many) {
    if (exists $value_hash{$item->$field}) {
      delete $value_hash{$item->$field};
    } else {
      $item->delete;
    }
  }

  my $add_to = "add_to_$many";
  foreach my $item (keys %value_hash) {
    $self->$add_to({ $field => $item });
  }
}


1;
