/Vector/Channel.pm
package Vector::Channel;
use Vector::DB;
use strict;

sub list {
	my ($name, %opts) = @_;
	my $dbh = Vector::DB::connect;
	my $channel_id = id($name);

	$opts{limit} = 10 unless exists $opts{limit};

	unless ($channel_id) {
		return ();
	}

	return @{$dbh->selectcol_arrayref('SELECT posts.post_id FROM posts LEFT JOIN threads ON posts.post_id = threads.post_id WHERE replyto IS NULL AND channel_id = ? ORDER BY updated ASC LIMIT ?', undef, $channel_id, $opts{limit})};
}

sub list_all {
	my ($name, %opts) = @_;
	my $dbh = Vector::DB::connect;

	my $channel_id = id($name);

	$opts{limit} = 100 unless exists $opts{limit};

	return @{$dbh->selectcol_arrayref('SELECT post_id FROM posts WHERE channel_id = ? ORDER BY ts ASC LIMIT ?', undef, $channel_id, $opts{limit})};
}

sub list_channels {
	my (%opts) = @_;
	my $dbh = Vector::DB::connect;

	$opts{limit} = 100 unless exists $opts{limit};

	return @{$dbh->selectcol_arrayref('SELECT channel_id FROM channels ORDER BY updated ASC limit ?', undef, $opts{limit})};
}

sub id {
	my ($name) = @_;
	my $dbh = Vector::DB::connect;

	my ($channel_id) = $dbh->selectrow_array('SELECT channel_id FROM channels WHERE name = ?', undef, $name);

	return $channel_id;
}

sub name {
	my ($channel_id) = @_;
	my $dbh = Vector::DB::connect;

	my ($name) = $dbh->selectrow_array('SELECT name FROM channels WHERE channel_id = ?', undef, $channel_id);

	return $name;
}

sub create {
	my ($name) = @_;
	my $dbh = Vector::DB::connect;

	$dbh->do('INSERT INTO channels (name) VALUES (?)', undef, $name);

	my ($channel_id) = $dbh->selectrow_array('SELECT channel_id FROM channels WHERE name = ?', undef, $name);

	return $channel_id;
}

sub update {
	my ($channel_id) = @_;
	my $dbh = Vector::DB::connect;

	$dbh->do('UPDATE channels SET updated=NOW() WHERE channel_id = ?', undef, $channel_id)
		or die "Could not update channel time for channel $channel_id";
}

1;