# -*- cperl -*-
# -----------------------------------------------------------------------------
# $Id: Curi.pm,v 1.1.1.1 2004/09/27 14:01:00 admin Exp $
# -----------------------------------------------------------------------------
# Curi: Celaenito URI
# -----------------------------------------------------------------------------
package Celaenito::Curi;
use strict;
use warnings;
use Carp;
use URI;
use UNIVERSAL qw(isa);
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(celaenito_uri curi_maketime);

sub curi_maketime ($) {
    my $epoch = shift;
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime($epoch);
    sprintf '%04d%02d%02d%02d%02d%02d', $year + 1900, $mon + 1, $mday, $hour, $min, $sec;
}

sub celaenito_uri (@) {
    # host_uri: URI->new('http://localhost/')
    # orig_uri: URI->new('http://www.example.org/foobar?deadbeef')
    # time: 'latest'
    # => URI->new('http://localhost/latest/http/www.example.org/foobar?deadbeef')
    my %args = @_;

    foreach my $key (qw[host_uri orig_uri]) {
	if ($_ = $args{$key}) {
	    if (isa $_ => 'URI') {
		$args{$key} = $_->canonical;
	    }
	    elsif (!ref $_) {
		$args{$key} = URI->new($_)->canonical;
	    }
	    else {
		croak "Arg{$key}: type error: ".ref($_);
	    }
	}
	else {
	    croak "Arg{$key} is missing";
	}
    }
    
    if (!defined $args{time}) {
	croak "Arg{time} is missing";
    }

    my $c_uri = $args{host_uri}->clone;
    my $o_uri = $args{orig_uri};
    $c_uri->path(sprintf(
	'/%s/%s/%s%s',
	$args{time},
	$o_uri->scheme,
	$o_uri->port == $o_uri->default_port ?
	  $o_uri->host : $o_uri->host_port,
	$o_uri->path));
    $c_uri->query($o_uri->query);
    $c_uri->fragment($o_uri->fragment);

    $c_uri;
}

1;
