<?php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/twitterCredentials.php';
require __DIR__ . '/cli_filter_application_inits.php';
require __DIR__ . '/cli_filter_application_consts.php';
require __DIR__ . '/../../parseTextAndMetadata.php';
require __DIR__ . '/../../parseUtils.php';
require __DIR__ . '/../../demosettings.php';


// Prepare simple wrapper function for htmlspecialchars.
function h($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

$handler_function = function ($status) {
	global $metadataDir, $textDir; //parameters for parseMetaDataLine in parseTextAndMetadata.php
    global $last_id;
	
	// Treat only tweets.
    if (!isset($status->text)) 
		return;
	
	$subfolder = date('Y-m-d-G');//this is necessary because one in an hour we move the folder to analyze
	$textDir = "text/$subfolder";
	$metadataDir = "extradata/$subfolder";
	echo "\r" . $status->created_at;
	$last_id = max($status->id_str, $last_id);
	$status_in_json = json_encode($status);
	if(KEEP_JSON) {
		file_put_contents("json/$status->id_str.json", $status_in_json);
	}
	$status = json_decode($status_in_json, true); //convert to associative array
    parseMetaDataLine($status); 
};

function save2text($statuses) 
{
	global $handler_function;
	foreach( $statuses as $status)
		$handler_function($status);
}

function avoid_rate_limit($timetowait)
{
	$start_time = time();
	echo "\nRate limit exceeded - wait $timetowait seconds until the next window\n";
	$errorlevel = executeCommand(__DIR__, BASH_Path . "./run_autosendfolder.bsh ");
	echo "\nAuto send folder returned $errorlevel\n"; //should be 0 if all O.K.
	$end_time = time();
	$timetowait= max(0, $timetowait-($end_time-$start_time));
	while($timetowait--) {
		if(FALSE === sleep(1)) die("\nCould not go to sleep\n");
		printf("\rWaiting %04s", $timetowait);
	}
	echo "\n";
}

use mpyw\Co\Co;
use mpyw\Co\CURLException;
use mpyw\Cowitter\Client;
use mpyw\Cowitter\HttpException;

// Set your timezone.
date_default_timezone_set('Asia/Damascus');

const KEEP_JSON = true;
const Rate_limit = 800; // Requests / 15-min window (app auth) [taken from here:https://dev.twitter.com/rest/reference/get/statuses/user_timeline]
const BASH_Path = "c:/cygwin64/bin/bash.exe "; //if running in cygwin use "/cygdrive/c/cygwin64/bin/bash.exe";

if( KEEP_JSON && !is_dir("json") ) {
	mkdir("json");
}

printf("\nstart stream\n");


   // Generate your TwistOAuth object.
try {
	// Create a client object
    $client = new Client([
        $CK,
        $CS,
        $AT,
        $AS,
    ]);
} catch (HttpException $e) { 
	$message = $e->getMessage();    // Message
	$code    = $e->getCode();       // Error code (-1 if not available)
	$status  = $e->getStatusCode(); // HTTP status code
	echo "\nmessage:$message";
	echo "\ncode:$code";
	echo "\nstatus:$status";
	die("Failed to create connection\n");
}
   	
//$users2follow = array( "i4i40" );
$users2follow=json_decode(file_get_contents("list-of-followers-id.json"));
echo "\nLoaded " . sizeof($users2follow) . " users ids\n";
$parameters = array ( 'count' => 10);
if ( !empty($last_id) )
	$parameters['since_id'] = "$last_id";	

echo "\nGet with last_id=$last_id\n";
$loop = Rate_limit;
foreach ($users2follow as $user) {
	if($loop === 0) {
		avoid_rate_limit(60*15); //wait for 15 minutes 
		$loop = Rate_limit;
	}
	
	try {
		// Get tweets on your home timeline
		// This method may throw Exception
		$parameters['user_id'] = "$user";
		$statuses = $client->get('statuses/user_timeline', $parameters);
		$time=date("i")%15;
		echo "\nGot:" . sizeof($statuses) . " statuses from user:$user time:$time loop:$loop\n";
		--$loop;
		save2text( $statuses );
	} catch (HttpException $e) { 
		echo "\nException in user: $user - " . $e->getMessage() . "\n";
        if(FALSE === strstr($e->getMessage(), "Not authorized"))
			avoid_rate_limit(60*15);		
	} catch (CURLException $e) {
    // cURL communication failed.
        $message = $e->getMessage();    // Message    (equivalent to curl_error())
        $code    = $e->getCode();       // Error code (equivalent to curl_errno())
    }
}

$NEW_INITS="<?php \$last_id=\"$last_id\"; ?>";
file_put_contents("cli_filter_application_inits.php", $NEW_INITS); //for later resurrection

avoid_rate_limit(1); //run_autosendfolder

?>
