package WinRT;
use 5.006;

use strict; $|++;
use Config;
use File::Glob;

# sequence is important!
our @EXPORT_OK = (qw/$RT $PERL $DB $HTTPD $RELAY/);
use vars @EXPORT_OK, '%WinRT';
use base 'Exporter';

$mod_perl::VERSION ||= 0;
*Win32::GetShortPathName = sub { $_[0] };

%WinRT = ( basepath => Win32::GetShortPathName($INC{'Config.pm'}) );
$WinRT{basepath} =~ s|perl/lib.*$||i;
$WinRT{path} = "$WinRT{basepath}/../Request Tracker/winrt";

# initialize all variables via submodules
foreach my $var (map { substr($_, 1) } @EXPORT_OK) {
    last unless $^O eq 'MSWin32';

    no strict 'refs';
    my $pkg = __PACKAGE__;
    eval "use $pkg\::$var; 1" or die $@;
    ${"$pkg\::$var"} = "$pkg\::$var"->new(WinRT->{basepath});
    *{"$pkg\::$var\::AUTOLOAD"} = \&AUTOLOAD;
}

sub NewObject {
    my ($class, $base, $dir, $file) = @_;

    # first, locate RT under $base
    my $path = (
	sort grep { $file ? -e "$_/$file" : -d }
	File::Glob::bsd_glob("$base/$dir*")
    )[0] or die "Can't find $base/$dir/$file!";

    return bless({path => $path}, $class);
}

sub Spawn {
    my ($self, $cmd, @args) = @_;
    my $obj;

    $cmd =~ s{/}{\\}g;

    my $args = join(' ', map qq("$_"), $cmd, @args);
    $args =~ s{/}{\\}g;

    require Win32::Process;
    Win32::Process::Create(
        $obj, $cmd, $args, 0, Win32::Process::NORMAL_PRIORITY_CLASS(), "."
    ) or die Win32::FormatMessage( Win32::GetLastError() );
    
    return $obj;
}

sub ReadFrom {
    my ($self, $file) = @_;

    local $/;
    open my $fh, '<', $file or die "Cannot read from $file: $!";
    return <$fh>;
}

sub WriteTo {
    my ($self, $file) = splice(@_, 0, 2);
    open my $fh, '>', $file or die "Cannot write to $file: $!";
    print $fh @_;
}


sub BasePath {
    return $WinRT{basepath};
}

our $AUTOLOAD;
sub AUTOLOAD {
    my $self = shift;
    
    my $method = $AUTOLOAD;
    $method =~ s/^.*:://;

    no strict 'refs';
    my $rv = join('/', $self->{path}, $method, @_);
    $rv =~ s|//+|/|g;
    return $rv;
}

1;
