# $Id: Save.pm,v 1.6 2002/05/22 01:57:41 muhri Exp $
# -*- perl -*-
package Pronto::Save;
use strict;
use File::Copy;
use SelfLoader;
use vars qw($last_dir);
$last_dir = undef;

1;
__DATA__
  
sub set_last_dir
{
    my ($dir) = @_;
    $dir =~ s/(.*)\://;
    my @tmp = split('/',$dir);
    if ($tmp[0] eq " ") { $tmp[0] = ""; }
    $last_dir = join('/',@tmp);
}    
    
sub save_message_as {
 	
	my (@selection, $msgid, $filename,);

	$msgid = &Pronto::MessageList::get_selected_msgid();
 	if (!$msgid) {
     		&main::err_dialog(_("Select the message You want to save!"));
     		return 1; 
 	}

  	$filename = "message$msgid.txt";

	my $msg_src = &Pronto::Data::Message::get_source($msgid);
	&init_fs_window(undef,$filename,$msg_src,"message");

	return 1;

}

sub save_attachment
{
    my ($widget, $fs_window, $source) = @_;
    my ($filename);
    $filename = $fs_window->get_filename();
    set_last_dir($fs_window->selection_text->get());
    $fs_window->destroy;
    my $source_fh = FileHandle->new("$source", "r") or return &main::err_dialog(_("Could not open the source file $source"));
    my $to_fh = FileHandle->new("$filename", "w") or return &main::err_dialog(_("Could not open $filename for writing!"));
    copy($source_fh, $to_fh) or return &main::err_dialog(_("Couldn't copy $source to $filename\n"));
    $source_fh->close() if $source_fh;
    $to_fh->close() if $to_fh; 
    return 1;
}	

sub file_selection_ok {
 	
	my ($widget, $fs_window, $msg_src) = @_;
 	my ($filename);
 	$filename = $fs_window->get_filename();
        set_last_dir($fs_window->selection_text->get());
	$fs_window->destroy;
	open(TMP,">$filename") or return &main::err_dialog(_("Couldn't open $filename for writing!"));;
	print TMP $msg_src;
	close(TMP);

	return 1;

}

sub init_fs_window {
  
  	my ($widget, $filename, $source, $message) = @_;
  	if (!$filename) { $filename=""; }
  	my ($fs_window);
  	$fs_window = new Gtk::FileSelection _("Save File...");
  	$fs_window->position(-mouse);
  	$fs_window->signal_connect("destroy", sub {$fs_window->destroy;});
  	$fs_window->signal_connect("delete_event" => \&Gtk::false);
 	if ($message && $message eq "message") {
		$fs_window->ok_button->signal_connect("clicked", \&file_selection_ok, $fs_window, $source);
  	} else {
		$fs_window->ok_button->signal_connect("clicked", \&save_attachment, $fs_window, $source);
	}	
	$fs_window->cancel_button->signal_connect("clicked", sub {$fs_window->destroy;});

    if ($last_dir) {
	$fs_window->set_filename($last_dir."/");
    }
    
    $fs_window->selection_entry->set_text($filename);

    $fs_window->show;
    return 1;
}

1;
