#!/usr/bin/perl

use LWP::UserAgent;
use HTTP::Request;
use Config::INI::Simple;
use PerlTray;
use Win32::TieRegistry;
use File::Basename;

chdir(dirname(PerlTray::exe()));
$Registry->Delimiter("/");
my $balance = 0;
my $traffic = '0 Mb';
my $not_first = 0;

my $config = new Config::INI::Simple;
$config->read ("config.ini"); 

sub update {
	my $user_agent = LWP::UserAgent->new;
	$user_agent->timeout(10);
	$user_agent->agent('RSBalancer/0.1.2');
	my $http_request = HTTP::Request->new(GET => 'https://'.$config->{auth}->{login}.':'.$config->{auth}->{password}.'@rs.net.ua:8543/abonent/abonent/main.html');
	my $result = $user_agent->request($http_request);
	if ($result->is_success) {
		local $_ = $result->content;
		@balance[$i++] = $1	while(m/<td><b>(.*)<\/b><\/td>/ig);
		$traffic = $1 if (m/Internet \((.*)\)/ig);
		$balance = @balance[1]*-1;
		undef $user_agent; undef $result; undef $http_request;
	}
	else {
		if (!$not_first) {$not_first = 1; &update;} else {MessageBox($config->{lang}->{error_con}, $config->{lang}->{error_title}, MB_ICONERROR); $error = 1; sleep(1);}
	}
}

sub autostart_get {	
    if ($Registry->{"HKEY_LOCAL_MACHINE/Software/Microsoft/".'Windows/CurrentVersion/Run//RSB'}) {return 1} else {return 0};
}

sub autostart_change {
	if (&autostart_get){delete $Registry->{"HKEY_LOCAL_MACHINE/Software/Microsoft/".'Windows/CurrentVersion/Run//RSB'}}
	else{$Registry->{"HKEY_LOCAL_MACHINE/Software/Microsoft/".'Windows/CurrentVersion/Run//RSB'}=PerlTray::exe()}
}

sub PopupMenu  {
	if (&autostart_get) {$as = $config->{lang}->{as_deact}} else {$as = $config->{lang}->{as_act}};
    return [
		[$config->{lang}->{menu_about}, sub {MessageBox(" Version: 0.0.2 \n Made by Vladimir Smirnoff \n http://orl.sumy.ua",'About RSBalancer',MB_ICONINFORMATION) }],
		["--------"],[$as,\&autostart_change],["--------"],
		[$config->{lang}->{menu_stat}, "Execute 'https://stat.rs.net.ua'"],
		[$config->{lang}->{menu_exit}, "exit"]
	]
}

sub Click {
	if (!$updating) {
		$updating = 1;
		&update; 
		if (!$error){Balloon($config->{lang}->{bal_balance}.' '.$balance.' '.$config->{lang}->{bal_currency}."\n".$config->{lang}->{bal_traffic}.' '.$traffic, $config->{lang}->{bal_title}.' '.$config->{auth}->{login}, 'info', 1)};
		undef $updating;
	}
};

sub ToolTip {
	return $config->{lang}->{tooltip};
}

RegisterHotKey($config->{settings}->{hotkey}, \&Click);
SetIcon('menu');
