#!/usr/bin/perl

use Data::Dumper;
use Storable qw(lock_store lock_nstore lock_retrieve);

package CheatIndex;


sub new {
	my $class = shift;
	my $indexfile = shift;
	unless ( $indexfile && ( -f $indexfile ) ) {
		$indexfile = "admin/cheat_index.dat";
	}
	unless ( -f $indexfile )  {
		$indexfile = $ENV{DOCUMENT_ROOT} . "/megacheats/admin/cheat_index.dat";
	}

	if ( ! -f $indexfile ) {
		die "unable to find file $indexfile";
	}

	# Parse the groups file
	my $data = Storable::lock_retrieve($indexfile);
	$data->{file} = $indexfile;
	return bless $data, $class;
}

sub rename {
	my $self = shift;
	my $section = shift;
	my $id = shift;

	$self->update($section, $id);

	my $newname = shift;
	my $data = $self->{direct}{$section}{$id};

	my $oldinitial = substr($data->{name}, 0, 1);

	$data->{name} = $newname;

	my $newinitial = substr($data->{name}, 0, 1);

	delete $self->{indexed}{$section}{$oldinitial}{$id};
	$self->{indexed}{$section}{$newinitial}{$id} = $data;
}

sub update {
	my $self = shift;
	my $section = shift;
	my $id = shift;
	my $time = shift;
	$time ||= time;
	$self->{direct}{$section}{$id}{modifyTime} = $time;
}

sub submit {
	my $self = shift;
	my $section = shift;
	my $id = shift;
	my $time = shift;
	$time ||= time;
	$self->{direct}{$section}{$id}{submitTime} = $time;
}

sub create {
	my $self = shift;
	my $section = shift;
	my $name = shift;
	my $time = shift;

	my $data = {
		name => $name,
		createTime => $time,
	};

	my $id = 0;
	foreach (keys %{$self->{direct}{$section}}) {
		$id = $id < $_ ? $_ : $id;
	}

	$id ++;

	my $newinitial = substr($data->{name}, 0, 1);

	$self->{indexed}{$section}{$newinitial}{$id} = $data;
	$self->{direct}{$section}{$id} = $data;
}

sub delete {
	my $self = shift;
	my $section = shift;
	my $id = shift;

	my $data = $self->{direct}{$section}{$id};
	my $oldinitial = uc substr($data->{name}, 0, 1);
	delete $self->{indexed}{$section}{$oldinitial}{$id};
	delete $self->{direct}{$section}{$id};
}

sub DESTROY {
	my $self = shift;
	lock_store($self->{file});
}

sub urlencode {
  return map { s/ /+/g; s/([^+[:alnum:]])/%pack('C', $1)/g } @_ if (wantarray);
  my $woof = shift;
  $woof =~ s/([^[:alnum:]])/%pack('C', $1)/g;
  $woof =~ s/ /+/g;
  return $woof;
}

sub querystring {
  my $accrue;
  my $first = 1;
  foreach (keys %params) {
    if ($first) {
      $accrue .= "?";
    } else {
      $accrue .= "&";
    }
    $accrue .= "$_=";
    $accrue .= urlencode $params{$_};
  }
}

1;

