package Data::Query::Renderer::SQL::Naive;

use strictures 1;
use SQL::ReservedWords;
use Data::Query::Constants qw(
  DQ_IDENTIFIER DQ_OPERATOR DQ_VALUE DQ_JOIN DQ_ALIAS DQ_ORDER DQ_LITERAL
);

sub new {
  bless({ %{$_[1]||{}} }, (ref($_[0])||$_[0]))->BUILDALL;
}

sub BUILDALL {
  my $self = shift;
  $self->{reserved_ident_parts}
    ||= (
      our $_DEFAULT_RESERVED ||= { map +($_ => 1), SQL::ReservedWords->words }
    );
  $self->{quote_chars}||=[''];
  $self->{simple_ops}||=$self->_default_simple_ops;
  return $self;
}

sub _default_simple_ops {
  +{
    (map +($_ => 'binop'), qw(= > < >= <= != LIKE), 'NOT LIKE' ),
    (map +($_ => 'unop'), qw(NOT) ),
    (map +($_ => 'unop_reverse'), ('IS NULL', 'IS NOT NULL')),
    (map +($_ => 'flatten'), qw(AND OR) ),
    (map +($_ => 'in'), ('IN', 'NOT IN')),
    (map +($_ => 'between'), ('BETWEEN', 'NOT BETWEEN')),
    (apply => 'apply'),
  }
}

sub render {
  my $self = shift;
  $self->_flatten_structure($self->_render(@_))
}

sub _flatten_structure {
  my ($self, $struct) = @_;
  my @bind;
  [ do {
      my @p = map {
        my $r = ref;
        if (!$r) { $_ }
        elsif ($r eq 'ARRAY') {
          my ($sql, @b) = @{$self->_flatten_structure($_)};
          push @bind, @b;
          $sql;
        }
        elsif ($r eq 'HASH') { push @bind, $_; () }
        else { die "_flatten_structure can't handle ref type $r for $_" }
      } @$struct;
      join '', map {
        ($p[$_], (($p[$_+1]||',') eq ',') ? () : (' '))
      } 0 .. $#p;
    },
    @bind
  ];
}

# I presented this to permit strange people to easily supply a patch to lc()
# their keywords, as I have heard many desire to do, lest they infect me
# with whatever malady caused this desire by their continued proximity for
# want of such a feature.
#
# Then I realised that SQL::Abstract compatibility work required it.
#
# FEH.

sub _format_keyword { $_[0]->{lc_keywords} ? lc($_[1]) : $_[1] }

sub _render {
  $_[0]->${\"_render_${\(lc($_[1]->{type})||'broken')}"}($_[1]);
}

sub _render_broken {
  my ($self, $dq) = @_;
  require Data::Dumper::Concise;
  die "Broken DQ entry: ".Data::Dumper::Concise::Dumper($dq);
}

sub _render_identifier {
  die "Unidentified identifier (SQL can no has \$_)"
    unless my @i = @{$_[1]->{elements}};
  # handle single or paired quote chars
  my ($q1, $q2) = @{$_[0]->{quote_chars}}[0,-1];
  my $always_quote = $_[0]->{always_quote};
  my $res_check = $_[0]->{reserved_ident_parts};
  return [
    join
      $_[0]->{identifier_sep}||'.',
      map +(
        $_ eq '*' # Yes, this means you can't have a column just called '*'.
          ? $_    # Yes, this is a feature. Go shoot the DBA if he disagrees.
          : ( # reserved are stored uc, quote if non-word
              $always_quote || $res_check->{+uc} || /\W/
                ? $q1.$_.$q2
                : $_
            )
      ), @i
  ];
}

sub _render_value {
  defined($_[1]->{value})
    ? [ '?', $_[1] ]
    : [ 'NULL' ];
}

sub _operator_type { 'SQL.Naive' }

sub _render_operator {
  my ($self, $dq) = @_;
  my $op = $dq->{operator};
  unless (exists $op->{$self->_operator_type}) {
    $op->{$self->_operator_type} = $self->_convert_op($dq);
  }
  my $op_name = $op->{$self->_operator_type};
  if (my $op_type = $self->{simple_ops}{$op_name}) {
    return $self->${\"_handle_op_type_${op_type}"}($op_name, $dq);
  } elsif (my $meth = $self->can("_handle_op_special_${op_name}")) {
    return $self->$meth($dq);
  }
  if (my $argc = @{$dq->{args}}) {
    if ($argc == 1) {
      return $self->_handle_op_type_unop($op_name, $dq);
    } elsif ($argc == 2) {
      return $self->_handle_op_type_binop($op_name, $dq);
    }
  }
  die "Unsure how to handle ${op_name}";
}

sub _handle_op_type_binop {
  my ($self, $op_name, $dq) = @_;
  die "${op_name} registered as binary op but args contain "
      .scalar(@{$dq->{args}})." entries"
    unless @{$dq->{args}} == 2;
  [
    $self->_render($dq->{args}[0]),
    $op_name,
    $self->_render($dq->{args}[1]),
  ]
}

sub _handle_op_type_unop {
  my ($self, $op_name, $dq) = @_;
  die "${op_name} registered as unary op but args contain "
      .scalar(@{$dq->{args}})." entries"
    unless @{$dq->{args}} == 1;
  [
    '(',
    $op_name,
    $self->_render($dq->{args}[0]),
    ')',
  ]
}

sub _handle_op_type_unop_reverse {
  my ($self, $op_name, $dq) = @_;
  die "${op_name} registered as unary op but args contain "
      .scalar(@{$dq->{args}})." entries"
    unless @{$dq->{args}} == 1;
  [
    $self->_render($dq->{args}[0]),
    $op_name,
  ]
}

sub _handle_op_type_flatten {
  my ($self, $op_name, $dq) = @_;
  my @argq = @{$dq->{args}};
  my @arg_final;
  while (my $arg = shift @argq) {

    unless ($arg->{type} eq DQ_OPERATOR) {
      push @arg_final, $arg;
      next;
    }

    my $op = $arg->{operator};
    unless (exists $op->{$self->_operator_type}) {
      $op->{$self->_operator_type} = $self->_convert_op($arg);
    }
  
    if ($op->{$self->_operator_type} eq $op_name) {
      unshift @argq, @{$arg->{args}};
    } else {
      push @arg_final, $arg;
    }
  }
  my @sql = ('(', map +($self->_render($_), $op_name), @arg_final);
  $sql[-1] = ')'; # replace final AND or whatever with )
  \@sql;
}

sub _handle_op_type_in {
  my ($self, $op, $dq) = @_;
  my ($lhs, @in) = @{$dq->{args}};
  my @rhs = ('(', map +($self->_render($_), ','), @in);
  $rhs[-1] = ')';
  [ $self->_render($lhs), $op, @rhs ];
}

sub _handle_op_type_between {
  my ($self, $op_name, $dq) = @_;
  my @args = @{$dq->{args}};
  if (@args == 3) {
    my ($lhs, $rhs1, $rhs2) = (map $self->_render($_), @args);
    [ '(', $lhs, $op_name, $rhs1, 'AND', $rhs2, ')' ];
  } elsif (@args == 2 and $args[1]->{type} eq DQ_LITERAL) {
    my ($lhs, $rhs) = (map $self->_render($_), @args);
    [ '(', $lhs, $op_name, $rhs, ')' ];
  } else {
    die "Invalid args for between: ${\scalar @args} given";
  }
}

sub _handle_op_type_apply {
  my ($self, $op_name, $dq) = @_;
  my ($func, @args) = @{$dq->{args}};
  die "Function name must be identifier"
    unless $func->{type} eq DQ_IDENTIFIER;
  my $ident = do {
    # The problem we have here is that built-ins can't be quoted, generally.
    # I rather wonder if things like MAX(...) need to -not- be handled as
    # an apply and instead of something else, maybe a parenop type - but
    # as an explicitly Naive renderer this seems like a reasonable answer.
    local @{$self}{qw(reserved_ident_parts always_quote)};
    $self->_render_identifier($func)->[0];
  };
  [
    "$ident(",
    (map $self->_render($_), @args),
    ')'
  ]
}

sub _convert_op {
  my ($self, $dq) = @_;
  if (my $perl_op = $dq->{'operator'}->{'Perl'}) {
    for ($perl_op) {
      $_ eq '==' and return '=';
      $_ eq 'eq' and return '=';
      $_ eq '!' and return 'NOT';
    }
    return uc $perl_op; # hope!
  }
  die "Can't convert non-perl op yet";
}

sub _render_select {
  my ($self, $dq) = @_;
  die "Empty select list" unless @{$dq->{select}};

  # it is, in fact, completely valid for there to be nothing for us
  # to project from since many databases handle 'SELECT 1;' fine

  my @select = map [
    ($_->{type} eq DQ_ALIAS
      ? $self->_render_alias($_, $self->_format_keyword('AS'))
      : $self->_render($_)
    ),
   ','
  ], @{$dq->{select}};

  # we put the commas inside the [] for each entry as a hint to the pretty
  # printer downstream so now we need to eliminate the comma from the last
  # entry - we know there always is one due to the die guard at the top

  pop @{$select[-1]};

  return [
    $self->_format_keyword('SELECT'),
    \@select,
    # if present this may be a bare FROM, a FROM+WHERE, or a FROM+WHERE+GROUP
    # since we're the SELECT and therefore always come first, we don't care.
    ($dq->{from}
       ? ($self->_format_keyword('FROM'), @{$self->_render($dq->{from})})
       : ()
    )
  ];
}

sub _render_alias {
  my ($self, $dq, $as) = @_;
  # FROM foo foo -> FROM foo
  # FROM foo.bar bar -> FROM foo.bar
  if ($dq->{alias}{type} eq DQ_IDENTIFIER) {
    if ($dq->{alias}{elements}[-1] eq $dq->{as}) {
      return $self->_render($dq->{alias});
    }
  }
  return [
    $self->_render($dq->{alias}),
    $as || ' ',
    $self->_render_identifier({ elements => [ $dq->{as} ] })
  ];
}

sub _render_literal {
  my ($self, $dq) = @_;
  unless ($dq->{subtype} eq 'SQL') {
    die "Can't render non-SQL literal";
  }
  if ($dq->{literal}) {
    return [
      $dq->{literal}, @{$dq->{values}||[]}
    ];
  } elsif ($dq->{parts}) {
    return [ map $self->_render($_), @{$dq->{parts}} ];
  } else {
    die "Invalid SQL literal - neither 'literal' nor 'parts' found";
  }
}

sub _render_join {
  my ($self, $dq) = @_;
  my ($left, $right) = @{$dq->{join}};
  die "No support for ON yet" if $dq->{on};
  die "No support for LEFT/RIGHT yet" if $dq->{outer};
  [ $self->_render($left), ',', $self->_render($right) ];
}

sub _render_where {
  my ($self, $dq) = @_;
  my ($from, $where) = @{$dq}{qw(from where)};
  [
    ($from ? $self->_render($from) : ()),
    $self->_format_keyword('WHERE'),
    $self->_render($where)
  ]
}

sub _render_order {
  my ($self, $dq) = @_;
  my @ret = (
    $self->_format_keyword('ORDER BY'),
    $self->_render($dq->{by}),
    ($dq->{direction} ? $self->_format_keyword($dq->{direction}) : ())
  );
  my $from;
  while ($from = $dq->{from}) {
    last unless $from->{type} eq DQ_ORDER;
    $dq = $from;
    push @ret, (
      ',',
      $self->_render($dq->{by}),
      ($dq->{direction} ? $self->_format_keyword($dq->{direction}) : ())
    );
  }
  unshift @ret, $self->_render($from) if $from;
  \@ret;
}

1;
