<?php
/**
 * @copyright Gmed Srl
 * @author Sciarrone Riccardo <riccardos@gmed.it>
 * 
 * programma che invia a Mosaiq gli studi elaborati
 */



// Report all errors except E_NOTICE
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


include __DIR__ . "/../conf/config.inc.php";
include __DIR__ . "/../include/basic_function.php";
include __DIR__ . "/../include/dcm_function.php";
//include __DIR__ . "/tags_to_modify_calculation.php";

$this_pid = __DIR__ . "/../cron_" . basename(__FILE__, ".php") . ".pid";
if (file_exists($this_pid)) {
    unlink($this_pid);
}

$pid_name = "send_studies";
check_pid($pid_name);


if( isset($GLOBALS["db_error"]['default_db']) ){
    WriteLog("Errore DB: " . $GLOBALS["db_error"]['default_db'], "ERROR");
    die_proc("Errore DB: " . $GLOBALS["db_error"]['default_db'], $pid_name);
}


echoo("\nELABORO GLI STUDI in stato 5\n\n");
WriteLog("ELABORO GLI STUDI in stato 5", process_logfile, "INFO");



$single_orthanc_id = "";
if ( isset($argv[1]) || isset($_GET["id"]) ) {
    // da elaborare UN singolo studio
    $single_orthanc_id = " AND orthanc_id = '" . 
                            ( isset($argv[1]) ? $argv[1] : $_GET["id"] )
                            . "' ";
}



$studies = query_select("   SELECT  *
                            FROM    dcm_study
                            WHERE   status = 5 
                                    $single_orthanc_id
                            ORDER BY id ");


if ( !isset($studies[0]['id']) || IsNull($studies[0]['id']) ) {
    // NULLA DA elaborare
    WriteLog("NULLA DA ELABORARE", send_logfile, "INFO");
    die_proc("NULLA DA ELABORARE \n", $pid_name);
}


foreach ($studies as $q_study) {
    echoo( "Elaboro " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " su destinazione " . dcm_destination . "\n" );
    WriteLog( "Elaboro " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " su destinazione " . dcm_destination, send_logfile, "INFO" );
    

    /*
     * PEERS
     * 
     * For instance:

            $ curl http://localhost:8042/peers/peer/store -d '6e2c0ec2-5d99c8ca-c1c21cee-79a09605-68391d12'
            {
            "Description" : "REST API",
            "FailedInstancesCount" : 0,
            "InstancesCount" : 46,
            "ParentResources" : [ "6e2c0ec2-5d99c8ca-c1c21cee-79a09605-68391d12" ],
            "Peer" : [ "http://localhost:8042/" ]
            }
            $ curl http://localhost:8042/modalities/self/store -d '6e2c0ec2-5d99c8ca-c1c21cee-79a09605-68391d12'
            {
            "Description" : "REST API",
            "FailedInstancesCount" : 0,
            "InstancesCount" : 46,
            "LocalAet" : "ORTHANC",
            "ParentResources" : [ "6e2c0ec2-5d99c8ca-c1c21cee-79a09605-68391d12" ],
            "RemoteAet" : "ORTHANC"
            }
     */

    // 2023-03-09 - SR 
    $POSTFIELDS = '{
                        "Resources" : ["' . $q_study["orthanc_id"] . '"],
                        "Synchronous" : false,
                        "LocalAet" : "' . LocalAet . '",
                        "MoveOriginatorAet": "' . MoveOriginatorAet . '",
                        "MoveOriginatorID": ' . MoveOriginatorID . ',
                        "Timeout": 10,
                        "StorageCommitment": false
                    }';
    
    // 2023-03-09 - aggiunto il metodo
    $cmd = orthanc_url . '/' . dcm_store_method . '/' . dcm_destination . '/store';

    echoo("\n\ncomando: $cmd\n\n");
    echoo($POSTFIELDS . "\n\n");
    
    $result = call_orthanc($cmd, "C-STORE", false, 'POST', $POSTFIELDS);

    if( isset($result["error"]) ){
        // studio non trovato! passo alla prossima
        echoo("ERRORE STORE " . $result["error"] . " - " .$result["descr"] . "\n<hr/>\n");
        WriteLog("ERRORE  STORE  " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " " . $result["error"] . " - " .$result["descr"], send_logfile, "ERROR");
        continue;
    }
    elseif ( isset($result["Path"]) ){
        $update_sql = " UPDATE  dcm_study 
                        SET     status = 6,
                                job_id = '" . $result["Path"] . "',
                                archive_date = '" . date("Y-m-d H:i:s") . "' 
                        WHERE   id = " . $q_study["id"];
        $upd_chan = query_execute($update_sql);
        echoo("Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " IN '6 - STORE IN CORSO' " . $result["Path"] . "\n<hr/>\n");
        WriteLog("Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " IN '6 - STORE IN CORSO' " . $result["Path"], send_logfile, "INFO");            
    }
    else {
        echoo("\nNON SO COSA FARE con questa Risposta:\n");
        echoo($result, TRUE);
        echoo("<hr/>\n");
        WriteLog("send_studies    Problema con Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . "\nNON SO COSA FARE con questa Risposta:\n" .$result, send_logfile, "INFO");
    }
    
    
}


echoo("\n\n<hr>FINE ELABORAZIONE\n\n");

kill_pid($pid_name);