#! /usr/bin/perl -w

use XML::Twig;
use DBI;  

my $database='DDR';
my $hostname='localhost';                
my $dsn = "DBI:mysql:database=$database;host=$hostname";
my $user='ddr_admin';
my $password='ddr_2014';
my $dbh = DBI->connect($dsn, $user,$password);
 

my $name_to_ids = $dbh->selectall_hashref("SELECT `Gene Name`,id_entity FROM entity","Gene Name") || die $dbh->errstr;  ;


my $twig=XML::Twig->new(   
    twig_handlers => 
      { a=>\&change_link,
        
      },
    pretty_print => 'indented',                # output will be nicely formatted
    empty_tags   => 'html',                    # outputs <empty_tag />
                         );
  $twig->parsefile( '../Web/svg/DDR_complete.svg');

  sub change_link
    { my( $twig, $link)= @_;  
      my $href= $link->{'att'}->{"xlink:href"}; 
      #say STDERR $href;
      if ($href=~/\.\.\/Php\/result.php\?GeneSearch=(.+)$/){
         my $gene_name=$1; 
         #say STDERR $gene_name;
         if ( $id=($name_to_ids->{$gene_name}->{'id_entity'}) ){ 
            say STDERR "$gene_name succesfully changed by id: $id";
            $href="../Php/display?id=".$id;  
            $link->set_att('xlink:href',$href) ;
         }  else {
               say STDERR "$gene_name in link $href DOES NOT EXISTS IN DATABASE";
         }  
         #$twig->flush;;
      }
    }
    
   $twig->print;