package TheCommon;
use TheDatabase;
use TheHTTP;
use TheSMTP;
use CGI;
use strict;

main->new()->main();
1;

sub new {
    local *FILE;
    my $config = {};
    open(FILE, '.config') or die "Couldn't open '.config': $!";
    while (defined($_ = <FILE>)) {
        chomp;
        if (m/^([^\#].*?)=(.*)$/gos) {
            $config->{$1} = $2;
        } # else no '=' or leading '#'; ignore line
    }
    close(FILE);
    return bless {
        'config' => $config,
        'query' => CGI->new(),
        'database' => TheDatabase->new($config->{dbconfig}, $config->{dbusername}, $config->{dbpassword}),
        'http' => TheHTTP->new($config->{name}),
    }, shift;
}

sub main {
    die "no main() function";
}

sub newPassword {
    my $self = shift;
    # Based on SopPasswd, a generator for Sort-of-pronounceable passwords, version 0.1
    # Written by Mark A. Pors, mark@dreamzpace.com, www.dreamzpace.com

    my $wordlen = 7; # desired length of the password
    my $sublen = 3; # length of the word chunks that create the password (must be < $wordlen)

    my @dict;

    local *DICT;
    open(DICT, "<$self->{config}->{dict}") || die "Cannot open dictionary file: $!";
    while (<DICT>) {
        chomp;
        push(@dict, $_);
    }

    my @sub = ();
    my $word = '';
    my $parts = int($wordlen/$sublen);

    for (my $i=0; $i < $parts; $i++) {
	do {
	    $sub[$i] = substr($dict[int(rand @dict)], 0, $sublen);
	} until (length $sub[$i] >= $sublen);
	$word .= lc $sub[$i];
    }

    my $left = $wordlen % $sublen;
    $word .= substr(int rand (10**($wordlen-1)), 0, $left);

    return $word;
}

sub getCookie {
    my $self = shift;
    return scalar $self->{query}->cookie('referrer');
}

sub setCookie {
    my $self = shift;
    $self->{http}->addHeader('Set-Cookie', 
                             $self->{query}->cookie(-name => 'referrer', -value => $_[0], -expires => '+10y'));
}
