#!/usr/local/bin/perl

# These are the variables passed to each function call.
#
# $_[0] = name for this module (surely you already know this, but still)
# $_[1] = sending nickname
# $_[2] = sending username
# $_[3] = sending hostmask
# $_[4] = sending channel (or botnick in case of PM)
# $_[5] = current value for $modchan
# $_[6] = current value for $botnick
# $_[7] = first argument given in IRC
# $_[8] = second argument given in IRC etc.

package translate;
use LWP::Simple; # Requires libwww-perl to be installed.
use LWP::UserAgent;

$appid = "GET_YOUR_OWN_BING_APP_ID";

sub to {

	$url = "https://api.microsofttranslator.com/v2/Http.svc/Translate?";
	@string = splice(@_, 8, @_);
	$url = $url . "appId=" . $appid . "&to=" . $_[7] . "&text=";
	
	foreach $word (@string) {
		$url = $url . $word . "%20";
	}

	chop $url; chop $url; chop $url;
	$result = get($url);
	$result =~ s/(<string(.+?)>)|(<\/string>)|(\n)|(\r)//ig;

	if($result eq "") {
		nanobot::msg($_[4], "Error: No result. (Probably wrong language code.)");
	} else {
		nanobot::msg($_[4], $result);
	}
}

sub detect {
	$url = "https://api.microsofttranslator.com/v2/Http.svc/Detect?";
	@string = splice(@_, 7, @_);
	$url = $url . "appId=" . $appid . "&text=";
	
	foreach $word (@string) {
		$url = $url . $word . "%20";
	}

	chop $url; chop $url; chop $url;

	$result = get($url);

	$result =~ s/(<string(.+?)>)|(<\/string>)|(\n)|(\r)//ig;

	nanobot::msg($_[4], "Detected: $result");
}

sub public {
	@public = ("help", "to", "detect");
}

sub help {
	nanobot::snd("NOTICE $_[1] :Translation module: !translate.to en Translates a line to English.");
	nanobot::snd("NOTICE $_[1] :!translate.to de Translates a line to German etc.");
	nanobot::snd("NOTICE $_[1] :!translate.detect detects language of input line.");
	nanobot::snd("NOTICE $_[1] :http://wiki.insomnia247.nl/wiki/Nanobot_translate for language codes");
}

1;
