<?php

include_once 'S3QLgoodies.php';
$url = 'http://ibl.mdanderson.org/edu';
$key = 'aOOJK3qQRS10gpg';
$project_id = 530;
$verbCollectionID = 534;
$filename = 'Antibiogramdatabase.txt';
insertRules($url, $key, $project_id, $verbCollectionID, $filename);
function insertRules($url, $key, $project_id, $verbCollectionID, $filename)
{
    $s3ql = array('url' => $url, 'key' => $key, 'select' => '*', 'from' => 'collections', 'where' => array('project_id' => $project_id), 'format' => 'php');
    list($urlQ, $collection) = S3DBcall($s3ql);
    $allcollections = array();
    $allids = array();
    for ($j = 0; $j < count($collection); $j++) {
        array_push($allcollections, $collection[$j]['name']);
        array_push($allids, $collection[$j]['collection_id']);
    }
    $s3ql = array('url' => $url, 'key' => $key, 'select' => '*', 'from' => 'items', 'where' => array('collection_id' => $verbCollectionID), 'format' => 'php');
    list($urlQ, $verbs) = S3DBcall($s3ql);
    $allverbs = array();
    $allverbIds = array();
    for ($k = 0; $k < count($verbs); $k++) {
        array_push($allverbs, $verbs[$k]['notes']);
        array_push($allverbIds, $verbs[$k]['item_id']);
    }
    $c = file($filename);
    for ($i = 0; $i <= count($c); $i++) {
        $d = explode(chr(9), $c[$i]);
        if ($d[0] && $d[1] && $d[2]) {
            $rules[$file->getBasename('.json')] = json_decode(file_get_contents($file->getRealPath()), true);
        }
    }
    return $rules;
}
/**
 * @param string $fileName
 * @param array  $rules
 *
 * @return bool
 */
function insertRules($fileName, array $rules = [])
{
    $startTag = '/*INSERT_START*/';
    $endTag = '/*INSERT_END*/';
    $content = file_get_contents($fileName);
    $content = preg_replace($regexp = sprintf('#%s(.*)%s#s', quotemeta($startTag), quotemeta($endTag)), $startTag . var_export($rules, true) . $endTag, $content);
    return false !== file_put_contents($fileName, $content);
}
$directory = __DIR__ . '/../Resources/rules';
$fileName = __DIR__ . '/../src/RuleProvider/DefaultRuleProvider.php';
$rules = getRules($directory);
$result = insertRules($fileName, $rules);
$ruleCount = array_reduce($rules, function ($count, $rules) {
    return $count + count($rules);
}, 0);
if ($result) {
    printf("Written %d rules into '%s'.\n", $ruleCount, $fileName);
} else {
    printf("Error writing rules into '%s'.\n", $fileName);
}