package Dojo::Controller::Data;
use Mojo::File 'path';
use Mojo::JSON qw(decode_json encode_json);
use Mojo::Base 'Mojolicious::Controller';
use Dojo::Support qw{ dmph merge_hash load_module };
use Net::Telnet; 

  my $server_name = ""; 
  our $t;  #telnet server object
  my $data_path = path('lib/Dojo/Model/Data')->make_path;
sub simple{
  my $c=shift;
  my $n=$c->param("dreq")//"";
  my $json = {status => "304"};
  $json = { srv =>$c->config->{radio_server} } if $n =~m/^radio$/ ;
  $json = candy() if $n =~m/^candy$/ ;
  $json = decode_json($data_path->child("$n")->slurp)
    if $n=~m/^podcast\/podcast.json$/;
  $c->render(json=>$json);
}

sub admin{
  my $c=shift;
  my $n=$c->param("dreq")//"";
  my $json = {status => "304"};
  $json = ($c->dbv->rmsgid ($c->param('id')))[0] if ($n =~m/^mensajes$/); 
  $json = ($c->dbv->ecourse($c->param('id')))[0] if ($n =~m/^ecourse$/); 
  $json = ($c->dbv->qcourse($c->param('id')))[0] if ($n =~m/^qcourse$/); 
  $json = ($c->dbv->qplace ($c->param('id')))[0] if ($n =~m/^qplace$/); 
  $c->render(json=>$json);
}
#==== candy  =====================================================
sub candy{
  my $c=shift;
  my $r="-1";
  $server_name = $c->config->{chat_srv}; 
  if (connectT()) {
      $r = isOn()    if ($c->param("command") =~/^isOn$/);
      $r = turnOn()  if ($c->param("command") =~/^on$/);
      $r = turnOff() if ($c->param("command") =~/^off$/);
   disconnectT(); 
  }
  else {$r="connection error";};
  $c->render(json => {a=>$r});
}  

  sub turnOff{  
    grep(/Result: true/,join('',sendT('host:deactivate("'.$server_name.'")')))?1:0 
      unless (isOn()==0);
  } 
  sub turnOn{
    grep(/Result: true/,join('',sendT('host:activate("'.$server_name.'")')))?1:0 
      unless (isOn()==1);
  } 

 sub isOn{return grep(/\s$server_name/,sendT("host:list()"))? 1:0; }  

sub sendT{ 
    commandT(shift);  
    my @r = $t->getlines(All=>0);
    return @r
} 
sub connectT{ 
    $t = new Net::Telnet (  Port=>5582, Timeout=>1, Errmode=>'return' );
    #  $t = new Net::Telnet (  Port=>5582, Timeout=>1, Errmode=>'die' );
    return 1 if $t->open();
    return 0;
} 
sub commandT{ 
    $t->getlines(All=>0);#empty buffer  
    $t->print(shift); #run istruction
} 
sub disconnectT{ $t->close();}  

#=========================================================
1; 
__END__ 


