#!/usr/local/bin/perl -w
###########################################
# hit-detect - Analyze historical viewcount
# Mike Schilli, 2014 (m@perlmeister.com)
###########################################
use strict;
use DBI;
use DBD::SQLite;
use Statistics::LineFit;
use YAML qw( LoadFile );
use JSON qw( to_json );

my $dbh = DBI->connect( 
  "dbi:SQLite:dbname=viewcounts.db", 
  "", "", { RaiseError => 1} );

my $videos = 
  LoadFile( "youtube-watch.yml" );

for my $video ( @$videos ) {
  my $sth = $dbh->prepare( 
    "SELECT views from views 
     WHERE video_id = ? ORDER BY 
     queried ASC" );
  $sth->execute( $video->{ id } );

  my @xvalues = ();
  my @yvalues = ();

  my $x = 1;
  while ( my @row = 
          $sth->fetchrow_array ) {
    push @xvalues, $x;
    push @yvalues, $row[0];
    $x++;
  }

  my $last_x = pop @xvalues;
  my $last_y = pop @yvalues;

  my $fit = Statistics::LineFit->new();
  $fit->setData (\@xvalues, \@yvalues) or 
    die "Invalid data";

  my ($intercept, $slope) = 
    $fit->coefficients();

  my $y_predicted = $intercept + 
                    $last_x * $slope;

  if( abs( $last_y - $y_predicted ) > 
                             3 * $slope ) {
    print 
    "Hooray, $video->{ name } is a hit!\n";
  }
}
