package ISPMan::IMAP;
use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $IMAP $Config);



require Exporter;

@ISA = qw(Exporter AutoLoader);
@EXPORT = qw();
$VERSION = '0.01';

use ISPMan::Config;
use ISPMan::Log;



sub new {
   my $proto = shift;
   my $class = ref($proto) || $proto;   
   my $self;
   $self->{'Config'}=ISPMan::Config->new();
   return bless $self, $class;
}



sub connect{
   my $self=shift;
   my $server=shift;
   
   
   unless ($server){
      log_event("No server passed to Connect");
      return;
   }

   if (! $self->{'imap_connections'}{$server}){
      log_event("connecting to $server");
      if (! $self->{'imapModuleLoaded'}){
         require  IMAP::Admin;
         $self->{'imapModuleLoaded'}++;
      }

      $self->{'imap_connections'}{$server}=IMAP::Admin->new(
               'Server' => $server,  
               'Login' => $self->{'Config'}{'imapAdminUsername'},
               'Password' => $self->{'Config'}{'imapAdminPass'},
               );
   };
   
   $self->{'imap_connections'}{"_current_server_"}=$self->{'imap_connections'}{$server};
   return $self->{'imap_connections'}{$server};
}



sub try{
   my $self=shift;
   my $err=shift;
   if ($err != 0) {
      print $self->{'imap_connections'}{"_current_server_"}->{'Error'} , "\n";
   } else {
      return 1;
   }
}                          


sub delete {
   my $self=shift;
   my $mailbox=shift;
   my $server=shift;
   
   my $imap=$self->connect($server);
   $mailbox=($mailbox=~/^user\./)?$mailbox:"user.$mailbox";
   log_event("Trying to remove $mailbox from $server as $self->{'Config'}{'imapAdminUsername'}");
   if ($self->try($imap->set_acl($mailbox,  $self->{'Config'}{'imapAdminUsername'}, "d") )){
      if ($self->try($imap->delete($mailbox))) {
         log_event(" $mailbox deleted from  $server ");
         return 1;
      }
   }
   return 0;
}


sub add {
   my $self=shift;
   my $mailbox=shift;
   my $server=shift;
   my $imap=$self->connect($server);
   $mailbox=($mailbox=~/^user\./)?$mailbox:"user.$mailbox";
   log_event("Trying to add  $mailbox to  $server ");
   if ($self->try($imap->create($mailbox))){
      log_event(" $mailbox added to   $server ");
      return 1;
   }
   return 0;
}



# Preloaded methods go here.

# Autoload methods go after =cut, and are processed by the autosplit program.

1;
__END__
# Below is the stub of documentation for your module. You better edit it!

=head1 NAME

ISPMan::IMAP - Perl extension for blah blah blah

=head1 SYNOPSIS

  use ISPMan::IMAP;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for ISPMan::IMAP was created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head1 AUTHOR

A. U. Thor, a.u.thor@a.galaxy.far.far.away

=head1 SEE ALSO

perl(1).

=cut
