package GCBorrowings;

###################################################
#
#  Copyright 2005 Tian
#
#  This file is part of GCfilms.
#
#  GCfilms is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  GCfilms is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with GCfilms; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
###################################################

use strict;
use Gtk2;

{
    package GCBorrowersDialog;
    use base "Gtk2::Dialog";

    sub initValues
    {
        use locale;
        
        my $self = shift;
        my $keepPrevious = shift;

        my @borrowers;
        my @emails;

        if ($keepPrevious)
        {
            foreach my $line(@{$self->{people}->{data}})
            {
                push @borrowers, $line->[0];
                push @emails, $line->[1];
            }
        }
        else
        {
            @borrowers = split m/\|/, $self->{options}->borrowers;
            @emails = split m/\|/, $self->{options}->emails;
        }
        
        @{$self->{people}->{data}} = ();
        my %directory;
        
        for (my $i = 0; $i < scalar(@borrowers); $i++)
        {
            $directory{$borrowers[$i]} = $emails[$i];
        }
        
        my @keys = sort keys %directory;
        @keys = reverse @keys if $self->{reverse};
        foreach (@keys)
        {
            my @infos = [$_, $directory{$_}];
            push @{$self->{people}->{data}}, @infos;
        }
        $self->{people}->select(0);
        
        (my $template = $self->{options}->template) =~ s/<br>/\n/g;
        $self->{mailTemplate}->get_buffer->set_text($template);
        
        $self->{subject}->set_text($self->{options}->subject);
   }
    
   sub saveValues
   {
        my $self = shift;
       
        my $borrowers = '';
        my $emails = '';
        foreach (@{$self->{people}->{data}})
        {
            $borrowers .= $_->[0].'|';
            $emails .= $_->[1].'|';
        }
        $borrowers =~ s/.$//;
        $emails =~ s/.$//;
        $self->{options}->borrowers($borrowers);
        $self->{options}->emails($emails);
        
        my $buffer = $self->{mailTemplate}->get_buffer;
        (my $template = $buffer->get_text($buffer->get_start_iter,
						 $buffer->get_end_iter, 1)) =~ s/\n/<br>/g;
        $self->{options}->template($template);
 
        $self->{options}->subject($self->{subject}->get_text);
        
        $self->{options}->save;
    }
   
    sub show
    {
        my $self = shift;

        $self->initValues;
        
        $self->SUPER::show();
        $self->show_all;
        
        if ($self->run eq 'ok')
        {
            $self->saveValues;
        }
        $self->hide;
    }

    sub removeCurrent
    {
        my $self = shift;
        my @idx = $self->{people}->get_selected_indices;
                
        if ($^O =~ /win32/i)
        {
            my @newData;
            my $i = 0;
            foreach (@{$self->{people}->{data}})
            {
                push @newData, [$_->[0], $_->[1]] if $i != $idx[0];
                $i++;
            }
            @{$self->{people}->{data}} = @newData;
        }
        else
        {
            splice @{$self->{people}->{data}}, $idx[0], 1;
        }
    }
    
    sub add
    {
        my $self = shift;
        
        my $dialog = new Gtk2::Dialog($self->{parent}->{lang}->{BorrowersAdd},
                                                        $self,
                                                        [qw/modal destroy-with-parent/],
                                                        @GCDialogs::okCancelButtons
                                                    );
        
        my $table = new Gtk2::Table(2,2,0);
                                                    
        my $labelName = new Gtk2::Label($self->{parent}->{lang}->{BorrowersName});
        $table->attach($labelName, 0, 1, 0, 1, 'expand', 'fill', 5, 5);
        my $name = new Gtk2::Entry;
        $table->attach($name, 1, 2, 0, 1, 'expand', 'fill', 5, 5);
 
        my $labelEmail = new Gtk2::Label($self->{parent}->{lang}->{BorrowersEmail});
        $table->attach($labelEmail, 0, 1, 1, 2, 'expand', 'fill', 5, 5);
        my $email = new Gtk2::Entry;
        $table->attach($email, 1, 2, 1, 2, 'expand', 'fill', 5, 5);
       
        $dialog->vbox->pack_start($table,1,1,0);
        $dialog->vbox->show_all;
                                                    
        if ($dialog->run eq 'ok')
        {
            unshift @{$self->{people}->{data}}, [$name->get_text, $email->get_text];
        }
        
        $dialog->destroy;
    }
    
    sub sort
    {
        my $self = shift;

        $self->{reverse} = 1 - $self->{reverse};

        $self->{people}->get_column(0)->set_sort_indicator(1);
        $self->{people}->get_column(0)->set_sort_order($self->{reverse} ? 'descending' : 'ascending');
        $self->initValues(1);
    }

    sub new
    {
        my ($proto, $parent) = @_;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new($parent->{lang}->{BorrowersTitle},
                              $parent,
                              [qw/modal destroy-with-parent/],
                              @GCDialogs::okCancelButtons
                            );

        bless ($self, $class);
 
        $self->set_modal(1);
		$self->set_position('center');
        $self->set_default_size(400,400);

        $self->{reverse} = 0;

        $self->{parent} = $parent;
        $self->{options} = $parent->{options};

        my $hbox = new Gtk2::HBox(0,0);
        
        $self->{people} = new Gtk2::SimpleList($parent->{lang}->{BorrowersName} => "text",
                                                $parent->{lang}->{BorrowersEmail} => "text");
        $self->{people}->set_column_editable(1, 1);
#        $self->{people}->set_headers_clickable(1);
        $self->{people}->set_rules_hint(1);
        $self->{people}->get_column(0)->signal_connect('clicked' => sub {
                $self->sort;
            });
        $self->{people}->get_column(0)->set_sort_indicator(1);
        $self->{people}->get_column(0)->set_clickable(1);
        for my $i (0..1)
        {
            $self->{people}->get_column($i)->set_resizable(1);
        }
        $self->{order} = 1;
        $self->{sort} = -1;

        my $scrollPanelList = new Gtk2::ScrolledWindow;
        $scrollPanelList->set_policy ('never', 'automatic');
        $scrollPanelList->set_shadow_type('etched-in');
        $scrollPanelList->add($self->{people});
        
        my $vboxButtons = new Gtk2::VBox(0,0);
        my $addButton = Gtk2::Button->new_from_stock('gtk-add');
        $addButton->signal_connect('clicked' => sub {
                $self->add;
            });
        my $removeButton = Gtk2::Button->new_from_stock('gtk-remove');
        $removeButton->signal_connect('clicked' => sub {
                $self->removeCurrent;
            });
            
        #my $editButton = new Gtk2::Button($parent->{lang}->{BorrowersEdit});
        $vboxButtons->pack_start($addButton,0,0,5);
        $vboxButtons->pack_start($removeButton,0,0,5);
        #$vboxButtons->pack_start($editButton,0,0,0);
       
        $hbox->pack_start($scrollPanelList,1,1,10);
        $hbox->pack_start($vboxButtons,0,0,10);

        my $labelTemplate  = new Gtk2::Label($self->{parent}->{lang}->{BorrowersTemplate});
        $self->{mailTemplate} = new Gtk2::TextView;
        $self->{mailTemplate}->set_editable(1);
        $self->{mailTemplate}->set_wrap_mode('word');
        my $scrollTemplate = new Gtk2::ScrolledWindow;
        $scrollTemplate->set_border_width(0);
        $scrollTemplate->set_shadow_type('in');
        $scrollTemplate->set_policy('automatic', 'automatic');
        $scrollTemplate->set_size_request(-1,80);
        $scrollTemplate->add($self->{mailTemplate});

        my $hboxSubject = new Gtk2::HBox(0,0);
        my $labelSubject = new Gtk2::Label($self->{parent}->{lang}->{BorrowersSubject});
        $self->{subject} = new Gtk2::Entry;
        $hboxSubject->pack_start($labelSubject,0,0,0);
        $hboxSubject->pack_start($self->{subject},0,0,5);
        
        $self->vbox->pack_start($hbox,1,1,10);
        $self->vbox->pack_start($labelTemplate,0,0,10);
        $self->vbox->pack_start($hboxSubject,0,0,10);
        $self->vbox->pack_start($scrollTemplate,1,1,10);
        
        my $label1 = new Gtk2::Label($self->{parent}->{lang}->{BorrowersNotice1});
        $label1->set_alignment(0,0);
        my $label2 = new Gtk2::Label($self->{parent}->{lang}->{BorrowersNotice2});
        $label2->set_alignment(0,0);
        my $label3 = new Gtk2::Label($self->{parent}->{lang}->{BorrowersNotice3});
        $label3->set_alignment(0,0);
        $self->vbox->pack_start($label1,0,0,0);
        $self->vbox->pack_start($label2,0,0,0);
        $self->vbox->pack_start($label3,0,0,0);
 
        return $self;
    }
    
}

{
    package GCBorrowedDialog;
    use base "Gtk2::Dialog";

    sub setList
    {
        my ($self, $movies) = @_;

        $self->{moviesList} = $movies;
        
        @{$self->{movies}->{data}} = ();
        
        foreach (@{$movies})
        {
            next if (!$_->{borrower}) || ($_->{borrower} eq 'none');
            my @infos = [ $_->{title}, $_->{borrower}, $_->{lendDate} ];
            push @{$self->{movies}->{data}}, @infos;
        }
        
        $self->{movies}->select(0);
        $self->{movies}->columns_autosize;

    }
    
    sub show
    {
        my $self = shift;

        for my $i (0..2)
        {
            $self->{movies}->get_column($i)->set_sort_indicator(0);
        }
        $self->{order} = 1;
        $self->{sort} = -1;

        $self->SUPER::show();
        $self->show_all;
        $self->run;
        $self->hide;
    }

    sub new
    {
        my ($proto, $parent) = @_;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new($parent->{lang}->{BorrowedTitle},
                              $parent,
                              [qw/modal destroy-with-parent/],
                              'gtk-ok' => 'ok'
                            );

        bless ($self, $class);
        
        $self->{parent} = $parent;
 
        $self->set_modal(1);
		$self->set_position('center');
        $self->set_default_size(400,400);

        $self->{parent} = $parent;
        $self->{options} = $parent->{options};

        my $hbox = new Gtk2::HBox(0,0);
        
        $self->{movies} = new Gtk2::SimpleList(
                $parent->{lang}->{BorrowedMovie} => "text",
                $parent->{lang}->{BorrowedName} => "text",
                $parent->{lang}->{BorrowedDate} => "text");

        $self->{movies}->set_rules_hint(1);
        $self->{movies}->set_headers_clickable(1);
        
        $self->{order} = 1;
        $self->{sort} = -1;
        for my $i (0..2)
        {
            $self->{movies}->get_column($i)->set_sort_indicator(0);
            #$self->{movies}->get_column($i)->set_resizable(1);
            $self->{movies}->get_column($i)->signal_connect('clicked' => sub {
                    $self->sort($i);
                });
        }

        my $scrollPanelList = new Gtk2::ScrolledWindow;
        $scrollPanelList->set_policy ('never', 'automatic');
        $scrollPanelList->set_shadow_type('etched-in');
        $scrollPanelList->add($self->{movies});

        $self->vbox->pack_start($scrollPanelList,1,1,10);
 
        return $self;
    }
    
    sub sort
    {
        my ($self, $col) = @_;

        my @movies = @{$self->{moviesList}};

        for my $i (0..2)
        {
            $self->{movies}->get_column($i)->set_sort_indicator(0);
        }
        
        sub compareTitle
        {
            use locale;
            $a->{title} cmp $b->{title};
        }
        sub compareBorrower
        {
            use locale;
            $a->{borrower} cmp $b->{borrower};
        }
        sub compareLendDate
        {
            my ($day, $month, $year) = split m/\//, $a->{lendDate};
            my $dateA = join "_", $year, $month, $day;
            ($day, $month, $year) = split m/\//, $b->{lendDate};
            my $dateB = join "_", $year, $month, $day;
            $dateA cmp $dateB;
        }

        if ($self->{sort} == $col)
        {
            $self->{order} = 1 - $self->{order}
        }
        else
        {
            $self->{order} = 1;
        }
        
        @movies = sort compareTitle @movies if $col == 0;
        @movies = sort compareBorrower @movies if $col == 1;
        @movies = sort compareLendDate @movies if $col == 2;

        $self->{movies}->get_column($col)->set_sort_indicator(1);
        @movies = reverse @movies if ! $self->{order};
        $self->{movies}->get_column($col)->set_sort_order($self->{order} ? 'ascending' : 'descending');
        $self->setList(\@movies);
        $self->{sort} = $col;
    }

}

{
    package GCMailDialog;
    use base "Gtk2::Dialog";
    use Net::SMTP;
   
    sub show
    {
        my $self = shift;

        $self->SUPER::show();
        $self->show_all;
        
        if ($self->run eq 'ok')
        {
            my $mail = $self->formatMail;
            
            $self->sendMail($self->{from}->get_text, $self->{to}->get_text, $mail);
        }
        $self->hide;
    }

    sub sendMail
    {
        my ($self, $from, $to, $mail) = @_;

        $to =~ s/.*?<|>.*?//g;
        
        if ($self->{options}->mailer eq 'Sendmail')
        {
            $! = '';
            if (open(MAILER, "| sendmail -t -ba"))
            {
                print MAILER "$mail\r\n.\r\n";
                close MAILER;
            }
            else
            {
                my  $dialog = Gtk2::MessageDialog->new($self,
                        [qw/modal destroy-with-parent/],
                        'error',
                        'ok',
                        $self->{parent}->{lang}->{MailSendmailError}."\n\n$!");

                $dialog->set_position('center-on-parent');
                $dialog->run;
                $dialog->destroy;               
            }
        }
        else
        {
            my $smtp = Net::SMTP->new($self->{options}->smtp);
            if (!$smtp)
            {
                my  $dialog = Gtk2::MessageDialog->new($self,
                        [qw/modal destroy-with-parent/],
                        'error',
                        'ok',
                        $self->{parent}->{lang}->{MailSmtpError});
                  
                $dialog->set_position('center-on-parent');  
                $dialog->run;
                $dialog->destroy;
                return;
            }
            $smtp->mail($from);
            $smtp->to($to);
            $smtp->data;
            $smtp->datasend($mail);
            $smtp->dataend;
            $smtp->quit;
        }
    }
    
    sub formatMail
    {
        my $self = shift;
        
        my $mail = '';
        
        $mail .= "From: ".$self->{from}->get_text."\r\n";
        $mail .= "To: ".$self->{to}->get_text."\r\n";
        $mail .= "Subject: ".$self->{subject}->get_text."\r\n\r\n";
        
        my $buffer = $self->{mailContent}->get_buffer;
        
        $mail .= $buffer->get_text($buffer->get_start_iter, $buffer->get_end_iter, 1);
        
        $mail .= "\r\n";
    }
    
    sub new
    {
        my ($proto, $parent, $info) = @_;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new($parent->{lang}->{MailTitle},
                              $parent,
                              [qw/modal destroy-with-parent/],
                              @GCDialogs::okCancelButtons
                            );

        bless ($self, $class);
 
        $self->set_modal(1);
		$self->set_position('center');
        $self->set_default_size(400,400);

        $self->{parent} = $parent;
        $self->{options} = $parent->{options};

        my @borrowers = split m/\|/, $self->{options}->borrowers;
        my @emails = split m/\|/, $self->{options}->emails;

        my %directory;
        
        for (my $i = 0; $i < scalar(@borrowers); $i++)
        {
            $directory{$borrowers[$i]} = $emails[$i];
        }
              
        my $table = new Gtk2::Table(2,2,0);
        $table->set_row_spacings(10);
        $table->set_col_spacings(0);
        $table->set_border_width(10);
        
        my $labelFrom = new Gtk2::Label($parent->{lang}->{MailFrom});
        $self->{from} = new Gtk2::Entry;
        $self->{from}->set_text($parent->{options}->from);
        my $labelTo = new Gtk2::Label($parent->{lang}->{MailTo});
        $self->{to} = new Gtk2::Entry;
        $self->{to}->set_text($info->{borrower}.' <'.$directory{$info->{borrower}}.'>');
        my $labelSubject = new Gtk2::Label($parent->{lang}->{MailSubject});
        $self->{subject} = new Gtk2::Entry;

        my $subject = $parent->{options}->subject;
        $subject =~ s/%1/$info->{borrower}/g;
        $subject =~ s/%2/"$info->{title}"/g;
        $subject =~ s/%3/$info->{lendDate}/g;

        $self->{subject}->set_text($subject);
                
        $table->attach($labelFrom, 0, 1, 0, 1, 'shrink', 'fill', 0, 0);
        $table->attach($self->{from}, 1, 2, 0, 1, 'fill', 'fill', 0, 0);
        $table->attach($labelTo, 0, 1, 1, 2, 'shrink', 'fill', 0, 0);
        $table->attach($self->{to}, 1, 2, 1, 2, 'fill', 'fill', 0, 0);
        $table->attach($labelSubject, 0, 1, 2, 3, 'shrink', 'fill', 0, 0);
        $table->attach($self->{subject}, 1, 2, 2, 3, 'fill', 'fill', 0, 0);
       
        my $content = $parent->{options}->template;
        
        $content =~ s/<br>/\n/g;
        $content =~ s/%1/$info->{borrower}/g;
        $content =~ s/%2/"$info->{title}"/g;
        $content =~ s/%3/$info->{lendDate}/g;
        
        $self->{mailContent} = new Gtk2::TextView;
        $self->{mailContent}->set_editable(1);
        $self->{mailContent}->set_wrap_mode('word');
        $self->{mailContent}->get_buffer->set_text($content);
        my $scrollContent = new Gtk2::ScrolledWindow;
        $scrollContent->set_border_width(10);
        $scrollContent->set_shadow_type('in');
        $scrollContent->set_policy('automatic', 'automatic');
        $scrollContent->set_size_request(-1,80);
        $scrollContent->add($self->{mailContent});
                                            
        $self->vbox->pack_start($table,0,0,10);
        $self->vbox->pack_start($scrollContent,1,1,10);
 
        return $self;
    }
    
}

1;