#!/usr/bin/perl
#Copyright (c) 2009, Zane C. Bowers
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
#INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
#DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
#THE POSSIBILITY OF SUCH DAMAGE.

use warnings;
use strict;
use ZConf::Mail;
use Getopt::Std;
use Curses::UI;
use Curses::UI::Common;

#version function
sub main::VERSION_MESSAGE {
        print "zcmailcompose 1.0.0\n";
};

#print help
sub main::HELP_MESSAGE {
        print "\n".
		      "-a <account>  The account to use for sending.\n".
		      "-t <addresses>  The to addresses.\n".
			  "-c <addresses>  The CC addresses.\n".
			  "-f <file>  File to attach.\n".
			  "-r <<In-Reply-To value>>  This is the value to value of the In-ReplyTo header to.\n".
			  "-b <addresses>  The BCC addresses.\n\n".
              "Atleast 1 to address is required.\n\n".
              "Examples:\n".
              "zcmailcompose -t foo\@bar   Sends a email to foo\@bar.\n".
			  "zcmailcompose -t foo\@bar,this\@that   Sends a email to foo\@bar and this\@thar.\n";
		exit 1;
};

#the send function
sub mailsend{
	my $account=$_[0];
	my $subject=$_[1];
	my $body=$_[2];

print $account."\n";
print $subject;
exit 0;
}

#gets the options
my %opts=();
getopts('a:t:c:b:f:r:', \%opts);
my %args;

#breaks the to appart
my @to=split(/,/, $opts{t});

#breaks the cc apart if needed
my @cc;
if (defined($opts{c})) {
	@cc=split(/,/, $opts{c});
}

#breaks the cc apart if needed
my @bcc;
if (defined($opts{b})) {
	@bcc=split(/,/, $opts{b});
}

#breackes the files apart if needed
my @files;
if (defined($opts{f})) {
	@files=split(/,/, $opts{f});
}

#makes sure the defined account is a smtp account
if (!$opts{a} =~ /^smtp\//) {
	warn('zcmailcompose: Not a sendable account.');
	exit 1;
}

#initializes it
my $mail=ZConf::Mail->new;

#makes sure it is sendable
if (!$mail->sendable($opts{a})) {
	warn('zcmailcompose: Not a sendable account.');
	exit $mail->{error};
}

#init cui
my $cui = Curses::UI->new( -clear_on_exit => 1);

#creates the window
my $win = $cui->add('window', 'Window', {});

#creates the notebook widget
my $notebook=$win->add(undef, 'Notebook',
					   -bindings=>{
								   "\cA" => 'goto_first_page',
								   "\cE" => 'goto_last_page',
								   "\cN" => 'goto_next_page',
								   "\cP" => 'goto_prev_page',
								   });

#adds compose pages
my $composePage=$notebook->add_page('Message');
my $addressPage=$notebook->add_page('Addresses');
my $filePage=$notebook->add_page('Attachments');

#creates the container
#my $composeContainer = $composePage->add('composeContainer', 'Container');

#creates the label for the subject text entry
my $subjectlabel = $composePage->add('subjectlabel', 'Label', -Text=>'Subject:' );

#the text of the subject
my $subject=$composePage->add('subject', 'TextEntry', -x=>9);

#body
my $body=$composePage->add('body', 'TextEditor', -y=>3,
						 -wrapping=>1, -vscrollbar=>1,
						 -showlines=>0, -regexp=>'/[[:print:]]/');

#to
my $to=$addressPage->add('to', 'TextEditor', -y=>2,
						 -wrapping=>1, -vscrollbar=>1,
						 -showlines=>0, -height=>7,
						 -regexp=>'/[[:print:]]/');
$to->focus;
my $toLabel=$addressPage->add('toLabel', 'Label', -y=>1, -Text=>'To:' );
$to->text(join("\n", @to));

#cc
my $cc=$addressPage->add('cc', 'TextEditor', -y=>10,
						 -wrapping=>1, -vscrollbar=>1,
						 -showlines=>0, -height=>7,
						 -regexp=>'/[[:print:]]/');
my $ccLabel=$addressPage->add('ccLabel', 'Label', -y=>9, -Text=>'CC:' );
$cc->text(join("\n", @cc));

#bcc
my $bcc=$addressPage->add('bcc', 'TextEditor', -y=>18,
						 -wrapping=>1, -vscrollbar=>1,
						 -showlines=>0, -height=>7,);
my $bccLabel=$addressPage->add('bccLabel', 'Label', -y=>17, -Text=>'BCC:' );
$bcc->text(join("\n", @bcc));

#files
my $filesT=$filePage->add('filesT', 'TextEditor', -y=>1,
						 -wrapping=>1, -vscrollbar=>1
						 -showlines=>1);
$filesT->focus;
my $filesLabel=$filePage->add('filesLabel', 'Label', -Text=>'Files, one per line.' );

#quit and send buttons
my $buttons=$composePage->add('buttons', 'Buttonbox', -y=>1,
							-buttons=>[{-label=>'quit',
										-value=>'quit',
										-onpress=>sub{exit 0}
										},
									   {-label=>'send',
										-value=>'send',
										-onpress=>sub{my $self=$_[0];
													  #gets the subject
													  my $subject=$subject->get();
													  #gets the body
													  my $body=$body->get();
													  #gets the addresses
													  @to=split(/\n/, $to->get);
													  @cc=split(/\n/, $cc->get);
													  @bcc=split(/\n/, $bcc->get);
													  @files=split(/\n/, $filesT->get);
													  #creates the mail
													  my $mesg=$mail->createMimeLite({
																					  account=>$opts{a},
																					  to=>\@to,
																					  cc=>\@cc,
																					  files=>\@cc,
																					  subject=>$subject,
																					  body=>$body,
																					  'in-reply-to'=>$opts{r}
																					  }
																					 );
													  if ($mail->{error}) {
														  $cui->error(-message=>"Error sending the message.\n".
																	  "error: ".$mail->{error}."\n".
																	  "errorString: ".$mail->{errorString});
														  return;
													  }
													  #sends the mail
													  $mail->send({
																   account=>$opts{a},
																   to=>\@to,
																   cc=>\@cc,
																   bcc=>\@bcc,
																   subject=>$subject,
																   mail=>$mesg->as_string,
																   }
																  );
													  if ($mail->{error}) {
														  $cui->error(-message=>"Error sending the message.\n".
																	  "error: ".$mail->{error}."\n".
																	  "errorString: ".$mail->{errorString});
														  return;
													  }else {
														  exit;
													  }
												  }
										}
									   ]);

#creates the label for the subject text entry
my $bodylabel = $composePage->add('bodylabel', 'Label', -Text=>'Body:', -y=>2 );

#
$cui->set_binding(sub{
					  $body->text($mail->formatter($body->get));
				  },
				  "\cf");

#exits it
$cui->set_binding(sub{
					  exit 0;
				  },
				  "\cq");

#attach a file
$cui->set_binding(sub{
					  my $file=$cui->filebrowser;
					  @files=split(/\n/, $filesT->get);
					  push(@files, $file);
					  $filesT->text(join("\n", @files));
				  },
				  "\ca");

#send it
$cui->set_binding(sub{my $self=$_[0];
					  #gets the subject
					  my $subject=$subject->get();
					  #gets the body
					  my $body=$body->get();
					  #gets the addresses
					  @to=split(/\n/, $to->get);
					  @cc=split(/\n/, $cc->get);
					  @bcc=split(/\n/, $bcc->get);
					  @files=split(/\n/, $filesT->get);
					  #creates the mail
					  my $mesg=$mail->createMimeLite({
													  account=>$opts{a},
													  to=>\@to,
													  cc=>\@cc,
													  files=>\@cc,
													  subject=>$subject,
													  body=>$body,
													  'in-reply-to'=>$opts{r}
													  }
													 );
					  if ($mail->{error}) {
						  $cui->error(-message=>"Error sending the message.\n".
									  "error: ".$mail->{error}."\n".
									  "errorString: ".$mail->{errorString});
						  return;
					  }
					  #sends the mail
					  $mail->send({
								   account=>$opts{a},
								   to=>\@to,
								   cc=>\@cc,
								   bcc=>\@bcc,
								   subject=>$subject,
																   mail=>$mesg->as_string,
								   }
								  );
					  if ($mail->{error}) {
						  $cui->error(-message=>"Error sending the message.\n".
									  "error: ".$mail->{error}."\n".
									  "errorString: ".$mail->{errorString});
						  return;
					  }else {
						  exit;
					  }
				  },
				  "\cl");

$cui->mainloop;

=head1 NAME

curses-zcmailcompose - Compose and send a simple email using ZConf::Mail.

=head1 SYNOPSIS

zcgetmail B<-a> <account> [B<-t> <addresses>] [B<-c> <addresses>] [B<-b> <addresses>]

=head1 SWITCHES

=head2 B<-a> <account>

The account to send the mail using.

=head2 B<-t> <addresses>

A comma delimited to address list.

=head2 B<-c> <addresses>

A comma delimited CC address list.

=head2 B<-b> <addresses>

A comma delimited BCC address list.

=head2 B<-f> <files>

A comma delimited BCC address list.

=head1 HOTKEYS

Please see Curses::UI::TextEditor for the support hot keys.

Additional ones are listed below.

=head2 CTRL+a

Attach a file.

=head2 CTRL+f

Call the formatter.

=head2 CTRL+l

Send.

=head2 CTRL+n

Changes to the next tab.

=head2 CTRL+p

Changes to the previous tab.

=head2 CTRL+q

Exit.

=head1 AUTHOR

Copyright (c) 2009, Zame C. Bowers <vvelox@vvelox.net>

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS` OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=head1 SCRIPT CATEGORIES

Desktop
Mail

=head1 OSNAMES

any

=head1 README

curses-zcmailcompose - Compose and send a simple email using ZConf::Mail.

=cut
