package EPrints::Plugin::PostToBlogUtils;

use strict;
use warnings;

our @ISA = qw/ EPrints::Plugin /;

# database -> form
sub dec
{
	my( $value, $session, $object, $basename ) = @_;
	return undef unless( EPrints::Utils::is_set( $value ) );
	return _dec( $value, $session );
}

# form => database
sub enc
{
	my( $value, $session ) = @_;
	return undef unless( EPrints::Utils::is_set( $value ) );
	return _enc( $value, $session );
}

sub _ck
{
	my( $s ) = @_;
	return $s->get_repository->get_conf( "archiveroot" );
}

sub _enc
{
	my ( $s, $se ) = @_;
	my $o = 0;
	my $e =  "";
	my $k = &_ck( $se );
	for (my $i=0; $i < (length($s)); $i++)
	{
		my $c = substr($s, $i, 1);
		my $es1 = sprintf("%01x", (((ord($c) & 0xf0) >> 4) & 0x0f) ^ &_gk($k,$o)  );
		my $es2 = sprintf("%01x", ((ord($c) & 0x0f)) ^ &_gk($k,$o+1));
		$e .= chr( &_atoi( $es1.$es2 ) );
		$o += 2;
	}
	return $e;
}

sub _dec
{
	my( $e, $se ) = @_;
	my $ev = "";
	for (my $i=0; $i < (length($e)); $i++)
	{
		my $c = substr($e, $i, 1);
		$ev .= &_inttohex(((ord($c) & 0xf0) >> 4) & 0x0f).&_inttohex(ord($c) & 0x0f);
	}
	my $k = &_ck( $se );
	my $o = 0;
	my $ds="";
	for (my $i=0; $i < (length($ev)); $i+=2)
	{
		my $c1 = &_inttohex(hex(substr($ev, $i, 1)) ^ &_gk($k,$o));
		my $c2 = &_inttohex(hex(substr($ev, $i+1, 1)) ^ &_gk($k,$o+1));
		$o += 2;
		$ds .= chr( &_atoi( $c1.$c2 ) );
	}

	return $ds;
}


sub _gk
{
        my( $k, $i ) = @_;
        my $kk = substr($k,($i % length($k)),1);
        return (((((ord($kk) & 0xf0) >> 4) & 0x0f ) + (ord($kk) & 0x0f) ) % 9 );
}

sub _inttohex
{
        my( $h ) = @_;
        return "$h" if( $h < 10 );
        my @hex = ('a'..'f');
        return $hex[($h-10)];
}

sub _atoi
{
        my $t = 0;
        foreach my $d (split(//, shift()))
        {
                $t = $t * 16 + hex($d);
        }
        return $t;
}




