# milkbone - profile dialog

package Milkbone::File;

use Milkbone;

our $VERSION = '1.0';

use Tk::widgets qw(Frame);
use base qw(Tk::Toplevel);
use strict;
use warnings;

Construct Tk::Widget 'MBFile';

sub ClassInit
{
	my ($class, $mw) = @_;
	$class->SUPER::ClassInit($mw);
}

sub init
{
	my ($self, $mw, $data, $file, $type) = @_;

	$self->{text} = $self->Frame->pack(-expand => 1, -fill => 'both')->Scrolled(
		"Text", -scrollbars => 'oe', -background => 'white', -wrap => 'word')->
		pack(-expand => 1, -fill => 'both');
	
	$self->Button(-text => "Close", -command => [$self, "destroy"])->pack(-side => 'right');
	$self->Button(-text => "Save", -command => [$self, "on_save"])->pack(-side => 'right');

	$self->{text}->bind('<MouseWheel>', 
		[ sub { $_[0]->yview('scroll', -($_[1] / 120), 'units') }, Tk::Ev('D')]);

	$self->{text}->insert('0.0', $data);

	$self->{type} = $type;
	$self->{file} = $file;

	if($type eq "profile")
	{
		$self->configure(-title => "Edit Profile");
	}
	else
	{
		$self->configure(-title => "Edit Away Message");
	}

	$self->{text}->focus;
	hook("tk_seticon", -wnd => $self);
}

sub on_save
{
	my ($self) = @_;
	my $text = $self->{text}->get('0.0', 'end');

	$text = pre_save($text);

	open(OUT, ">" . $self->{file}) or die "couldn't open: $! " . $self->{file};
	print OUT $text;
	close(OUT);

	if($self->{type} eq "profile")
	{
		hook("protocol_set_prof", -data => $text);
	}
	elsif($self->{type} eq "away")
	{
		hook("protocol_set_away", -data => $text);
	}

	$self->destroy;
}

sub pre_save
{
	my ($text) = @_;

	$text =~ s/\n*$//g;
	$text =~ s/\n/<br>/gi;
	
	return $text;
}