package Gtk::pimPAQ::DateTimeEdit;
use PDA::pimPAQ qw(load_app debug);
use Gtk;
use strict;
use Date::Calc qw(:all);
use vars qw($DEBUG @ISA);
@ISA=qw(Gtk::Button);

sub init { my ($class)=@_;
  debug ("entered: $class") if $DEBUG;
  Gtk::Button->register_subtype( $class );
  debug ("left: $class") if $DEBUG;
}

sub GTK_CLASS_INIT { my ($class)=@_;
  debug ("entered: $class") if $DEBUG;
  $class->add_arg_type("date_string","GtkString",3);
  $class->add_arg_type("time_string","GtkString",3);
}

sub GTK_OBJECT_INIT { my ($s,$string_param)=@_;
  debug ("entered: $s,$string_param") if $DEBUG;
  foreach my $p (split(/\s+/,$string_param)) {
    $s->{_show}->{$p}=1 if $p eq 'date' || $p eq 'time';
  }
  $s->signal_connect("clicked" => sub {
    my $app=load_app('DateTimeSelect',$s->{_show});
    $app->select_datetime($s->{datetime});
    $app->{on_ok}=sub {
      $s->set_datetime($app->get_datetime);
    }
  });
  $s->set_datetime([]);
}

sub GTK_OBJECT_SET_ARG { my ($s,$arg,$id,$val)=@_;
  debug ("entered: $arg,$id,$val") if $DEBUG;
  if ($arg eq 'date_string') {
    @{ $s->{datetime} }[0,1,2]=[split('-',$val)];
  } elsif ($arg eq 'time_string') {
    @{ $s->{datetime} }[3,4,5]=[split(':',$val)];
  } else {
    warn "Unknown arg set: $arg,$id,$val\n";
  }
  $s->set_datetime;
}

sub GTK_OBJECT_GET_ARG { my ($s,$arg,$id)=@_;
  debug ("entered: $arg,$id") if $DEBUG;
  if ($arg eq 'date_string') {
    return join("-",@{ $s->{datetime} }[0,1,2])
  } elsif ($arg eq 'time_string') {
    return join(":",@{ $s->{datetime} }[3,4,5])
  } else {
    warn "Unknown arg get: $arg,$id\n";
    return undef;
  }
}

sub set_datetime { my ($s,$datetime)=@_;
  debug ("entered: $datetime") if $DEBUG;
  if (!$datetime) {
    $datetime=$s->{datetime};
  }
  my $datestr;
  if (!@$datetime) {
    $datestr="---";
  } else {
    my @formatstr;
    push @formatstr,"%x" if $s->{_show}->{date};
    push @formatstr,"%X" if $s->{_show}->{time};
    $datestr=POSIX::strftime(join(" ",@formatstr),
      $s->{datetime}->[5],      # sec
      $s->{datetime}->[4],      # min
      $s->{datetime}->[3],      # hour
      $s->{datetime}->[2]-1,    # mday
      $s->{datetime}->[1]-1,    # month
      $s->{datetime}->[0]-1900, # year
      -1,-1,-1                  # wday, yday, isdst
    )
  }
  $s->child->set($datestr);
  return $s->{datetime};
}

sub datetime {
  my $s=shift;
  $s->set_datetime(shift) if @_;
  $s->{datetime};
}

sub new {
  debug "entered: ".join(",",@_) if $DEBUG;
  return Gtk::Widget->new(@_);
}

1;
