package Camila::Commands;

use 5.006;
use strict;
use warnings;

use Data::Dumper;
use Camila::grammar;
use Camila::Prototype;

require Exporter;

our @ISA = qw(Exporter);
our %EXPORT_TAGS = ( 'all' => [ qw() ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw();


our $VERSION = '0.01';

sub _lambda {
  my ($vars,$def) = @_;
  my @vars = map {$_->{atomo}} @{$vars->{lista}};

  my $getvars = "my (".join(",",map {"\$$_"} @vars).") = \@_;\n";
  for (@vars) {
    $Camila::grammar::namespace{$_} = "UNKNOWN";
  }
  my $x = Camila::grammar::def2perl($def);
  my $type = ref($x->[0])?$x->[0]->show:$x->[0];

  return [ 'Function[$type]', "sub{\n$getvars$x->[1]}" ];
}

sub _if {
  my ($cond,$true,$false) = @_;

  $cond = Camila::grammar::def2perl($cond);
  $true = Camila::grammar::def2perl($true);
  if ($false) {
    $false = Camila::grammar::def2perl($false);
  }

  my $type = (ref($cond->[0]))?$cond->[0]->show:$cond->[0];
  if ($type eq "BOOL") {
    my $perl = "if ($cond->[1]) { $true->[1] } ";
    if ($false) {
      $perl .= " else { $false->[1] }";
    }

    my $l = (ref($true->[0]))?$true->[0]->show:$true->[0];
    if ($false) {
      my $r = (ref($false->[0]))?$false->[0]->show:$false->[0];
      if ($l eq $r) {
	return [$l,$perl]
      } else {
	return [[$l,$r],$perl];
      }
    } else {
      return [$l,$perl];
    }
  } else {
    print STDERR "If condition type should be bool, not '$type'";
    return [undef,""];
  }
}

sub _let {
  my ($vars,$res) = @_;
  my @vars = @{$vars->{lista}};

  my $perl = "";
  for my $var (@vars) {
    my ($id,$def) = @{$var->{lista}};
    $id = $id->{atomo};
    my $x = Camila::grammar::def2perl($def);
    $Camila::grammar::namespace{$id} = $x->[0];
    $perl.= "my \$$id = $x->[1];\n";
  }
  my $x = Camila::grammar::def2perl($res);
  return [$x->[0],"${perl}return $x->[1];\n"];
}


1;
__END__

