/**
 * Calcola o ri-calcola la cache dell'indice di rilevanza degli atti
 * Si può specificare il una data fino alla quale calcolare la rilevanza
 * Se sono passati degli ID (argomenti), sono interpretati come ID di atti e il calcolo è fatto solo per loro
 */
function run_opp_build_cache_atti($task, $args, $options)
{
    static $loaded;
    // load application context
    if (!$loaded) {
        task_loader();
        $loaded = true;
    }
    echo "memory usage: " . memory_get_usage() . "\n";
    $data = '';
    $verbose = false;
    $offset = null;
    $limit = null;
    if (array_key_exists('data', $options)) {
        $data = $options['data'];
    }
    if (array_key_exists('verbose', $options)) {
        $verbose = true;
    }
    if (array_key_exists('offset', $options)) {
        $offset = $options['offset'];
    }
    if (array_key_exists('limit', $options)) {
        $limit = $options['limit'];
    }
    if ($data != '') {
        $legislatura_corrente = OppLegislaturaPeer::getCurrent($data);
        $data_lookup = $data;
    } else {
        $legislatura_corrente = OppLegislaturaPeer::getCurrent();
        $data = date('Y-m-d');
        $data_lookup = OppActHistoryCachePeer::fetchLastData();
    }
    $msg = sprintf("calcolo rilevanza - fino a: %10s\n", $data);
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
    $start_time = time();
    if (count($args) > 0) {
        try {
            $atti_rs = OppAttoPeer::getRSFromIDArray($args);
        } catch (Exception $e) {
            throw new Exception("Specificare degli ID validi. \n" . $e);
        }
    } else {
        $atti_rs = OppAttoPeer::getAttiDataRS($data, $offset, $limit);
    }
    $n_atti = $atti_rs->getRecordCount();
    echo "memory usage: " . memory_get_usage() . "\n";
    $cnt = 0;
    while ($atti_rs->next()) {
        $a = $atti_rs->getRow();
        $atto_id = $a['id'];
        $tipo_atto_id = $a['tipo_atto_id'];
        $cnt++;
        $atto = OppAttoPeer::retrieveByPK($atto_id);
        if (!array_key_exists($tipo_atto_id, OppTipoAttoPeer::$tipi_per_indice)) {
            continue;
        }
        printf("%5d/%6d) %40s %d ... ", $cnt, $n_atti, OppTipoAttoPeer::$tipi_per_indice[$tipo_atto_id], $atto_id);
        $indice = OppIndiceRilevanzaPeer::calcola_rilevanza_atto($atto, $tipo_atto_id, $data, $verbose);
        // inserimento o aggiornamento del valore in opp_politician_history_cache
        $cache_record = OppActHistoryCachePeer::retrieveByDataChiTipoChiId($data_lookup, 'A', $atto_id);
        if (!$cache_record) {
            $cache_record = new OppActHistoryCache();
        }
        $cache_record->setLegislatura($legislatura_corrente);
        $cache_record->setChiTipo('A');
        $cache_record->setChiId($atto_id);
        $cache_record->setTipoAttoId($tipo_atto_id);
        $cache_record->setIndice($indice);
        $cache_record->setData($data);
        $cache_record->setUpdatedAt(date('Y-m-d H:i'));
        // forza riscrittura updated_at, per tenere traccia esecuzioni
        $cache_record->save();
        unset($cache_record);
        $msg = sprintf("%7.2f", $indice);
        echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
        $msg = sprintf(" [%4d sec] [%10d bytes]\n", time() - $start_time, memory_get_usage());
        echo pakeColor::colorize($msg, array('fg' => 'red', 'bold' => false));
    }
    $msg = sprintf("%d atti elaborati\n", $cnt);
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
}
/**
 * Prepara uno o più atti, specificati dall'id nell'elenco argomenti per un test
 * Vengono rimossi tutti i dati accessori:
 *  firme, assrgnazioni in commissione, documenti, tagging, esiti, interventi
 * Sono resettati il titolo e l'md5
 *
 * Necessario per pulire un oggetto prima di un test di upgrade
 */
function run_opp_prepare_ddl_for_test($task, $args, $options)
{
    static $loaded;
    // load application context
    if (!$loaded) {
        _loader();
    }
    $dry_run = false;
    if (array_key_exists('dry-run', $options)) {
        $dry_run = true;
    }
    $con = Propel::getConnection(OppAttoPeer::DATABASE_NAME);
    echo "memory usage: " . memory_get_usage() . "\n";
    $start_time = time();
    try {
        $atti_rs = OppAttoPeer::getRSFromIDArray($args, $con);
    } catch (Exception $e) {
        throw new Exception("Specificare degli ID validi. \n" . $e);
    }
    $n_atti = $atti_rs->getRecordCount();
    $cnt = 0;
    while ($atti_rs->next()) {
        $a = $atti_rs->getRow();
        $atto_id = $a['id'];
        print "atto: {$atto_id}\n";
        $atto = OppAttoPeer::retrieveByPK($atto_id);
        $atto->setTitolo("");
        $atto->setMd5("");
        $atto->save();
        print "  titolo e md5 annullat1\n";
        # firme
        $items = $atto->getOppCaricaHasAttos(null, $con);
        $nitems = count($items);
        foreach ($items as $cnt => $item) {
            $item->delete($con);
        }
        print "  {$nitems} firme rimosse\n";
        # assegnazioni
        $items = $atto->getOppAttoHasSedes(null, $con);
        $nitems = count($items);
        foreach ($items as $cnt => $item) {
            $item->delete($con);
        }
        print "  {$nitems} assegnazioni in commissione rimosse\n";
        # tag (sf_tagging)
        $items = $atto->getTagsAsTaggingObjects(null, $con);
        $nitems = count($items);
        foreach ($items as $cnt => $item) {
            $item->delete($con);
        }
        print "  {$nitems} tagging dell'atto rimossi\n";
        # documenti
        $items = $atto->getOppDocumentos(null, $con);
        $nitems = count($items);
        foreach ($items as $cnt => $item) {
            $item->delete($con);
        }
        print "  {$nitems} documenti allegati rimossi\n";
        # iter
        $last_iter = $atto->getLastIter();
        $last_iter->delete();
        # relazioni
        $items = $atto->getRelazioni();
        $nitems = count($items);
        foreach ($items as $cnt => $item) {
            $item->delete($con);
        }
        print "  {$nitems} relazioni rimosse\n";
        # esito sedute
        $items = $atto->getOppEsitoSedutas();
        $nitems = count($items);
        foreach ($items as $cnt => $item) {
            $item->delete($con);
        }
        print "  {$nitems} esiti rimossi\n";
        # interventi
        $items = $atto->getOppInterventos();
        $nitems = count($items);
        foreach ($items as $cnt => $item) {
            $item->delete($con);
        }
        print "  {$nitems} interventi rimossi\n";
        print "\n";
    }
    $msg = sprintf("fine task\n");
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
    $msg = sprintf(" [%4d sec] [%10d bytes]\n", time() - $start_time, memory_get_usage());
    echo pakeColor::colorize($msg, array('fg' => 'red', 'bold' => false));
}
/**
 * Genera i files di testo degli atti
 * $prefix/$atto_id
 */
function run_nltk_genera_files($task, $args, $options)
{
    static $loaded;
    // load application context
    if (!$loaded) {
        _loader();
    }
    $files_path = sfConfig::get('sf_data_dir') . DIRECTORY_SEPARATOR . "nltk";
    $act_types = array();
    $prefix = null;
    // usato per differenziare training, test e dev, è aggiunto prima dell'id
    $offset = null;
    $limit = null;
    if (array_key_exists('offset', $options)) {
        $offset = $options['offset'];
    }
    if (array_key_exists('limit', $options)) {
        $limit = $options['limit'];
    }
    if (array_key_exists('path', $options)) {
        $files_path = strtolower($options['path']);
    }
    if (array_key_exists('types', $options)) {
        $act_types = explode(",", $options['types']);
    }
    if (array_key_exists('prefix', $options)) {
        $prefix = strtolower($options['prefix']);
    }
    if (count($args) > 0) {
        try {
            $atti_rs = OppAttoPeer::getRSFromIDArray($args);
        } catch (Exception $e) {
            throw new Exception("Specificare degli ID validi. \n" . $e);
        }
    } else {
        $atti_rs = OppAttoPeer::getAttiTipoRS($act_types, $offset, $limit);
    }
    echo "memory usage: " . memory_get_usage() . "\n";
    $start_time = time();
    $msg = sprintf("generazione files dei testi degli atti\n");
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
    // loop principale
    $n_atti = $atti_rs->getRecordCount();
    $cnt = 0;
    while ($atti_rs->next()) {
        $a = $atti_rs->getRow();
        $atto_id = $a['id'];
        $tipo_atto_id = $a['tipo_atto_id'];
        $atto = OppAttoPeer::retrieveByPK($atto_id);
        if ($n_docs = $atto->countOppDocumentos()) {
            $docs = $atto->getOppDocumentos();
            // path di tutti i testi dei doc relativi all'atto
            $atto_txt = "";
            foreach ($docs as $doc) {
                $atto_txt .= $doc->getTesto();
            }
            unset($docs);
            $fh = fopen($files_path . "/" . $atto_id, 'w');
            fwrite($fh, $atto_txt);
            fclose($fh);
        }
        printf(" %d %d docs - ok (%d)\n", $atto_id, $n_docs, memory_get_usage());
        unset($atto);
        $cnt++;
    }
    $msg = sprintf("%d atti elaborati\n", $cnt);
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
    $msg = sprintf(" [%4d sec] [%10d bytes]\n", time() - $start_time, memory_get_usage());
    echo pakeColor::colorize($msg, array('fg' => 'red', 'bold' => false));
}