#!/usr/bin/perl

use strict;
use warnings;
use v5.14;

use DBI;

update2();

sub update2 {
    no autovivification qw(fetch);

    my $dbh = DBI->connect("dbi:SQLite:dbname=rss2html.sqlite", "", "");
    $dbh->{sqlite_unicode} = 1;

    my $feeds = $dbh->selectall_arrayref("select * from feeds where update_frequency is not null", { Slice => {} });
    my $seconds_per_week = 86400 * 7;
    for my $feed (@$feeds) {
	print "feed: $feed->{id} $feed->{title}\n";
	my $now = time();
	my $update_time = $now - $feed->{last_update};
	print "\t", "update_time: $update_time\n";
	my $start = $now - 4 * $seconds_per_week;
	my $items = $dbh->selectall_arrayref("select * from items where feed_id=? and issued >= ? order by issued",
	                                     { Slice => {} },
					     $feed->{id}, $start,
					    );
	my $first_issued = $items->[0]{issued} // $start;
	my $total_time = $now - $first_issued;
	print "\t", "total_time: $total_time\n";
	my $updates_in_interval = 0;
	for my $item (@$items) {
	    my $t = $item->{issued};
	    my $dt1 = $now - $t;
	    my $dt2 = $dt1 % $seconds_per_week;
	    if ($dt2 < $update_time) {
		$updates_in_interval++;
	    }
	}
	# normalize to one week
	$updates_in_interval *= $seconds_per_week / $total_time;
	$updates_in_interval += $update_time / $seconds_per_week; # add one update per week
	print "\t", "updates_in_interval: $updates_in_interval\n";

    }
}

# vim: tw=0