#------------------------------------------------------------------------------------------------------------------------------------------------
package fw::tools;
#------------------------------------------------------------------------------------------------------------------------------------------------

@ISA = qw(Exporter);



@EXPORT= qw(

suicide
print_file
get_file

to_ddmmyyyy
to_ansi_date

thumbnailize
thumbnailize_fixed

load_tabtxt_hash

		       
			);


use fw::env;        

use Data::Dumper;



#=============================================================================================================================================
# GET_FILE
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# get the content of a file in a string
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# INPUT PARAMETERS
#  0 : name of the file to get
# OUTPUT PARAMETERS
#  0 : content of the file
#==============================================================================================================================================
sub get_file
{
	my $filename = $_[0];
	my $content = "";

	open(FILE, $filename) or suicide ("GET_FILE : cannot open $filename");	
	
	while (<FILE>)
	{	
	   $content.= $_;
	}
	
	close(FILE);

	return $content;	
}

#==============================================================================================================================================
# PRINT_FILE
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# display the content of a file
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# INPUT PARAMETERS 
#  0 : name of the file to display
# OUTPUT PARAMETERS
#  none
#==============================================================================================================================================
sub print_file
{
	my $content = get_file($_[0]);
	print "$content";
}


#==============================================================================================================================================
# TO_DDMMYYY
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# convert ISO date (YYYY-MM-DD) to european format (DD-MM-YYYY)
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# INPUT PARAMETERS 
#  0 : string containing the date in the ANSI format (YYYY-MM-DD)
# OUTPUT PARAMETERS
#  0 : a tring in the european format (DD/MM/YYYY) 
#==============================================================================================================================================
sub to_ddmmyyyy
{
	my $datetime = $_[0] || ""; 
	my $notime = $_[1] || ""; 
  my ($date,$time) = split(/ /,$datetime);
  my ($yyyy,$mm,$dd) = split (/-/,$date); 
  my ($h,$min,$sec) = split (/:/,$time); 
  my $result="";
  
  if ($notime eq "withtime") 
  {
      $result = "$dd/$mm/$yyyy, ".$h."h".$min;
  }
  elsif ($notime eq "withtimeandbr") 
  {
      $result = "$dd/$mm/$yyyy, <br />".$h."h".$min;
  }
  else
  {
	   $result = "$dd/$mm/$yyyy";	
  }
  return $result;	
}


#==============================================================================================================================================
# TO_ANSI_DATE
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# convert european format (DD/MM/YYYY) to ISO date (YYYY-MM-DD)
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# INPUT PARAMETERS 
#  0 : string containing the date in the european format (DD/MM/YYYY)
# OUTPUT PARAMETERS
#  0 : a tring in the ANSI format (YYYY-MM-DD)
#==============================================================================================================================================
	sub to_ansi_date
{
	my $date = $_[0];
	
	my ($dd,$mm,$yyyy) = split (/\//,$date);
	
	$date = "$yyyy-$mm-$dd";	
	
	return $date;	
}

#==============================================================================================================================================
# SUICIDE
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# when an error occurs, display a nice message to the users
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# INPUT PARAMETERS 
#  0 : string containing the error message
# OUTPUT PARAMETERS
#  none (exit of the program)
#==============================================================================================================================================
sub suicide
{
	my $msg = $_[0]; 
    my $code = $_[1];
	my $is_web = $_[2];


	my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller();
	
  use Carp;	
  my $stack = Carp::longmess("Stack backtrace :");


	my $errormsg = "";
	
  if ($cfg{web_env}) {
	use fw::web;

$stack =~ s/\r*\n/<br>/g;			#Formatage de l'affichage de la chaine

  see();
	
	#Construction du message d'erreur
	$errormsg =  <<"EOM";
<html>
	<head

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<style type="text/css">*{background-color:#dd0000;font-family:courier new;}</style>
	</head>
<body>
	<h1>Guru Meditation</h1>
	<hr>
	<p><b>CODE : </b> $code </p>
</body>
EOM

	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);	

	my $moment =  sprintf("[%04d-%02d-%02d:%02d:%02d:%02d]",$year+1900,$mon+1,$mday,$hour,$min,$sec); 
	

$errormsg .= <<"EOT";
	<!--
		 $cfg{baseurl}
------------------------------------------------------------------------
		 $moment
		 $msg
------------------------------------------------------------------------
		 ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask)
		 [$stack]
-->
	</html>
EOT
  } else {
$errormsg = <<"EOT";
-------------------------------------------------------------------------------------
| Guru Meditation
-------------------------------------------------------------------------------------
Code :$code
-------------------------------------------------------------------------------------
$moment
$msg
-------------------------------------------------------------------------------------
		 ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask)
		 [$stack]
EOT
  }
	
  


	print "$errormsg";	
	
	exit();

}




#==============================================================================================================================================
# THUMBNAILIZE
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# create a thumbnail of a picture  
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# INPUT PARAMETERS 
#  0 : name of the picture
#  1 : path of the picture
#  2 : maximum width
#  3 : maximum height
# OUTPUT PARAMETERS
#  0 : value of the parameter, with ' quoted
#==============================================================================================================================================
sub thumbnailize
{
	use GD;		#Interface ÃÂÃÂ la librairie graphique GD
	GD::Image->trueColor(1);	#Dois utiliser les couleurs vrai. Chaque pixels de l'image sera codÃÂÃÂ sur 3 bytes et non 1.

	my $filename = $_[0];	#Nom de l'image
	my $upload_path = $_[1];	#Chemin absolu de cette image
	my $th_width = $_[2];	#Longeur maximum dÃÂÃÂsirÃÂÃÂ
	my $th_height = $_[3];	#Hauteur maximum dÃÂÃÂsirÃÂÃÂ
  my $th_suffix = $_[4] || "_thumb";
  if ($th_suffix eq " ") {$th_suffix = "";}
    my $other_dir = $_[5] || "";

  my $initial_th_height=$th_height;
  
	my $fullname = $upload_path."/".$filename;	#Nom complet du fichier

	my @splitted = split(/\./,$filename);	#DÃÂÃÂcoupage du nom du fichier
	my $ext = pop @splitted;	#Copie du dernier ÃÂÃÂlÃÂÃÂment qui est l'extension du fichier
	
	my $thumb_url = join(".",@splitted)."$th_suffix.".$ext;	#Reformation du nom du fichier qui sera enregistrer sur le serveur
       if ($other_dir ne "") {$upload_path=$other_dir;}
	my $thumb_filename = $upload_path."/".$thumb_url;	#Formation de l'adresse absolue de l'image

	my $error =  GD::Image->new($fullname) || 'error';
	if($error eq 'error')
	{
		return 'error';
	}
	
	my $full = GD::Image->new($fullname) || suicide("GD cannot open $fullname : [$!]");		#CrÃÂÃÂation d'une nouvelle image

	my ($fu_width,$fu_height) = $full->getBounds();		#RÃÂÃÂcupÃÂÃÂration de la longueur et de la hauteur de l'image reÃÂÃÂ¾ue en paramÃÂÃÂtre
  my ($transparent) = $full->transparent();		#RÃÂÃÂcupÃÂÃÂration de la couleur transparente
	my $prop = 1;	#Proportion de l'image

	if ($th_width > $fu_width) {$th_width = $fu_width;} #Si la longueur dÃÂÃÂsirÃÂÃÂ > grande que la longueur rÃÂÃÂelle
	if ($th_height > $fu_height) {$th_height = $fu_height;}	#Si la hauteur dÃÂÃÂsirÃÂÃÂ > grande que la hauteur rÃÂÃÂelle

	if ($fu_width >= $th_width && $fu_height >= $th_height) 
	{
	    if ($fu_width > $fu_height) 
		{
	        $prop = $fu_width / $th_width;	#Proportion des mesures de l'image rÃÂÃÂelle et l'image dÃÂÃÂsirÃÂÃÂe
	        $th_height = int ($fu_height / $prop);	#Redimensionnement de la hauteur en gardant la proportion longueur/hauteur
	        
	        #si la hauteur de la miniature calculÃÂÃÂe dÃÂÃÂpasse la hauteur maximum voulue pour la hauteur
	        if($th_height > $initial_th_height)
	        {
	             my $prop2=$initial_th_height/$th_height;
	             $th_width*=$prop2;
	             $th_height=$initial_th_height;
          }
	    } 
		else 
		{
	        $prop = $fu_height / $th_height;
	        $th_width = int ($fu_width / $prop);
	    }
	}

	my $thumb = GD::Image->new($th_width,$th_height,1);	#CrÃÂÃÂation d'une image avec les nouvelles valeurs proportionnelle
	



	$thumb->saveAlpha(1);
	$thumb->alphaBlending(0);
#	$thumb->transparent($transparent);
 	$thumb->copyResampled($full,0,0,0,0,$th_width,$th_height,$fu_width,$fu_height);	#Copie de l'image
	

	my $data;
	
	if ($ext =~ /[Jj][Pp][Ee]*[Gg]/) #Test de l'extension
	{
	    $data = $thumb->jpeg(100); 
	} 
	elsif ($ext =~ /[Pp][Nn][Gg]/) 
	{
#      $thumb->transparent($transparent);		#RÃÂÃÂcupÃÂÃÂration de la couleur transparente
	    $data = $thumb->png; 
	}

	open (THUMB,">$thumb_filename");	#Ouverture du fichier
	binmode THUMB;	#Mode binaire
	print THUMB $data;	#Enregistrement du fichier
	close THUMB;	#Fermeture

	return ($thumb_url,$th_width,$th_height,$fu_width,$fu_height);	#Retourne le nouveau nom du fichier et les informations sur la taille
}



#==============================================================================================================================================
# THUMBNAILIZE FIXED
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# create a thumbnail of a picture  
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# INPUT PARAMETERS 
#  0 : name of the picture
#  1 : path of the picture
#  2 : maximum width
#  3 : maximum height
#  4 : fix a dimension
# OUTPUT PARAMETERS
#  0 : value of the parameter, with ' quoted
#==============================================================================================================================================
sub thumbnailize_fixed
{
	use GD;		#Interface ÃÂÃÂ la librairie graphique GD
	GD::Image->trueColor(1);	#Dois utiliser les couleurs vrai. Chaque pixels de l'image sera codÃÂÃÂ sur 3 bytes et non 1.

	my $filename = $_[0];	#Nom de l'image
	my $upload_path = $_[1];	#Chemin absolu de cette image
	my $th_width = $_[2];	#Longeur maximum dÃÂÃÂsirÃÂÃÂ
	my $th_height = $_[3];	#Hauteur maximum dÃÂÃÂsirÃÂÃÂ
  my $th_suffix = $_[4] || "_thumb";
  my $fixed_dimension = $_[5] || "fixed_height";
  my $from_path = $_[6] || $filename;
  
#   print "<br />[$th_suffix][$fixed_dimension][$th_width][$th_height]";
  
  
	my $fullname = $from_path."/".$filename;	#Nom complet du fichier

	my @splitted = split(/\./,$filename);	#DÃÂÃÂcoupage du nom du fichier
	my $ext = pop @splitted;	#Copie du dernier ÃÂÃÂlÃÂÃÂment qui est l'extension du fichier
	
	my $thumb_url = join(".",@splitted)."$th_suffix.".$ext;	#Reformation du nom du fichier qui sera enregistrer sur le serveur
	my $thumb_filename = $upload_path."/".$thumb_url;	#Formation de l'adresse absolue de l'image

	my $full = GD::Image->new($fullname) || suicide("GD cannot open $fullname : [$!]");		#CrÃÂÃÂation d'une nouvelle image
	my ($fu_width,$fu_height) = $full->getBounds();		#RÃÂÃÂcupÃÂÃÂration de la longueur et de la hauteur de l'image reÃÂÃÂ¾ue en paramÃÂÃÂtre
#  my ($transparent) = $full->transparent();		#RÃÂÃÂcupÃÂÃÂration de la couleur transparente





	my $prop = 1;	#Proportion de l'image

	if($th_width > $fu_width) {$th_width = $fu_width;} #Si la longueur dÃÂÃÂsirÃÂÃÂ > grande que la longueur rÃÂÃÂelle
	if($th_height > $fu_height) {$th_height = $fu_height;}	#Si la hauteur dÃÂÃÂsirÃÂÃÂ > grande que la hauteur rÃÂÃÂelle
  
  my $decallage_x=0;
  my $decallage_y=0;
  my $thumb = GD::Image->new($th_height,$th_height);	#CrÃÂÃÂation d'une image avec les nouvelles valeurs proportionnelle
#   print "----> $fixed_dimension";
	if($fixed_dimension eq "fixed_height") 
	{
# 	  print "fu_width: $fu_width, fu_height: $fu_height";
    if($fu_width > $fu_height) 
		{
# 	        $prop = $fu_width / $fu_height;
          $prop = $fu_height / $fu_width ;		
	        $th_height = int ($prop * $th_height);
# 	        print " th width: $th_width";
	  } 
		else 
		{
	        $prop = $fu_height / $fu_width;	
	        $th_width = int ($th_height/$prop);
# 	        print " th width2: $th_width";
	  }
# 	  print "th_width: $th_width, th_height: $th_height";
	  
    $thumb = GD::Image->new($th_width,$th_height);	#CrÃÂÃÂation d'une image avec les nouvelles valeurs proportionnelle
#  	$thumb->transparent($transparent);
	$thumb->saveAlpha(1);
	$thumb->alphaBlending(0);
	  $thumb->copyResampled($full,0,0,0,0,$th_width,$th_height,$fu_width,$fu_height);
	}
	elsif($fixed_dimension eq "fixed_height_width") 
	{
    if($fu_width > $fu_height) 
		{
	        
# 	        print "[$fu_width][$fu_height][$th_width][$th_height]";
# 	        exit;
          
          $prop = $fu_width / $fu_height;	
	        $th_width = int ($prop * $th_height);
	        $thumb = GD::Image->new($th_height,$th_height);	#CrÃÂÃÂation d'une image avec les nouvelles valeurs proportionnelle
    #    	$thumb->transparent($transparent);
    	$thumb->saveAlpha(1);
	$thumb->alphaBlending(0);
	        $thumb->copyResampled($full,0,0,0,0,$th_width,$th_height,$fu_width,$fu_height);
	  } 
		else 
		{
	        $prop =  $fu_height / $fu_width;	
          $th_width=$th_height;
	        my $th_height_debordant=$prop * $th_height;
	        $thumb = GD::Image->new($th_width,$th_height);	#CrÃÂÃÂation d'une image avec les nouvelles valeurs proportionnelle
     #    	$thumb->transparent($transparent);
     	$thumb->saveAlpha(1);
	$thumb->alphaBlending(0);
	        $thumb->copyResampled($full,0,0,0,0,$th_width,$th_height_debordant,$fu_width,$fu_height);
	  }
  }
  
#   see();
#   print "fin";
#   exit;

	#Copie de l'image

	my $data;
	
	if ($ext =~ /[Jj][Pp][Ee]*[Gg]/) #Test de l'extension
	{
	    $data = $thumb->jpeg(100); 
	} 
	elsif ($ext =~ /[Pp][Nn][Gg]/) 
	{
#     $thumb->transparent($transparent);		#RÃÂÃÂcupÃÂÃÂration de la couleur transparente
	    $data = $thumb->png; 
	}

	open (THUMB,">$thumb_filename");	#Ouverture du fichier
	binmode THUMB;	#Mode binaire
	print THUMB $data;	#Enregistrement du fichier
	close THUMB;	#Fermeture

	return ($thumb_url,$th_width,$th_height,$fu_width,$fu_height);	#Retourne le nouveau nom du fichier et les informations sur la taille
}


sub load_tabtxt_hash
{
 my $file = $_[0];

 open (IN,$file) || suicide("cannot read $file : $!","Lang File Error");

 my %h = ();

while (<IN>) {
    my $line = $_;
    $line =~ s/\r*\n//g;
    my @t = split(/\t/,$line);

	$h{$t[0]} = $t[1];
}

 return %h;
}

1;