<?php
ini_set('display_errors',1);
$memcacheD = new Memcached;
$memcacheD->addServer('localhost',11211);
$link = mysqli_connect("localhost","jabramo","()mv1pnmq2v","vosk") or die("Error " . mysqli_error($mysLink));
$response = array(
    "error"=>0,
    "error_message"=>"",
    "data"=>array()
);

if(!isset($_GET['q']) || !isset($_GET['m'])) 
{ 
    $response["error"] = -1;
    $response["error_message"] = "Fila ou máquina não definidos.";
    print json_encode($response)."\n\n";
    exit();
}

$qName = $_GET['q'];
$mName = $qName.'_'.$_GET['m'];

$macData = array(
    'count'=>0,
    'last'=>Date('Y-m-d H:i:s')
);
$mData = $memcacheD->get($mName.'_data');
if($mData) $macData = json_decode($mData,true);
$qIRName = $qName."_isReading";
$tOut = 0;
while(isReading())
{
    $tOut++;
    usleep(100000);
    if($tOut > 30) {
        $response["error"] = 1;
        $response["error_message"] = "Nenhuma tarefa na fila. Tente novamente em 5 minutos.";
        print json_encode($response)."\n\n";
        exit();
    }
}
$memcacheD->set($qIRName,"1");

$nextRow = getNextRow();
if($nextRow) 
{
    $response['data'] = $nextRow;
    $response['data']['machine_name'] = $mName;
} else 
{
    $response["error"] = 2;
    $response["error_message"] = "Cache vazio. Tente novamente em 5 segundos.";
}
print json_encode($response);

$memcacheD->set($qIRName,"0");

function isReading()
{
    global $memcacheD,$qName,$mName;
    $qIRName = $qName."_isReading";
    if($memcacheD->get($qIRName)==1) return true;
    return false;
}

function getNextRow()
{
    global $memcacheD,$qName,$mName,$macData;
    $rCName = $qName."_rowsCache";
    $cachedRows = readCachedRows();
    if(count($cachedRows)==0)
    {
        sleep(5);
        $cachedRows = setCacheRowsFromDB();
        return false;
    }
    $nextRow = array_shift($cachedRows);
    $memcacheD->set($rCName,json_encode($cachedRows));
    $macData['count']+=1;
    $macData['last']=Date('Y-m-d H:i:s');
    $memcacheD->set($mName.'_data',json_encode($macData));
    /*
    if(count($cachedRows)<100)
    {
        $cachedRows = setCacheRowsFromDB();
    }
    */
    return $nextRow;
}

function readCachedRows()
{
    global $memcacheD,$qName,$mName;
    $rCName = $qName."_rowsCache";
    $cr = $memcacheD->get($rCName);
    $currentRows = array();
    if($cr) $currentRows = json_decode($cr,true);
    return $currentRows;
}

function setCacheRowsFromDB()
{
    global $memcacheD,$link,$qName,$mName;

    $rCName = $qName."_rowsCache";
    $cr = $memcacheD->get($rCName);
    $currentRows = array();
    if($cr) $currentRows = json_decode($cr,true);
    $dbRows = array();
    $dbQueries = getSqls();

    $resp = $link->query($dbQueries['select']);
    if($resp->num_rows > 0)
    {
        while($row = $resp->fetch_assoc())
        {
            ###### CUIDADO!!!! ATUALIZAR O NOME DO CAMPO ID NA LINHA ABAIXO
            $ids[] = $row['vfl_id'];
            $currentRows[] = $row;
        }
        $sqlUp = str_replace('***ids***',implode(',',$ids),$dbQueries['update']);
        $link->query($sqlUp);
    }
    
    $memcacheD->set($rCName,json_encode($currentRows));
}

function getSqls()
{
    global $qName,$mName;
    $sqls = array(
        'transc'=>array(
            'select'=>
            "
            SELECT 
                vsk_files.* 
            FROM 
                vsk_files INNER JOIN 
                vsk_channels ON vfl_chn_id = chn_id INNER JOIN
                vsk_schedule ON vfl_chn_id = sch_chn_id AND DATE_FORMAT(vfl_start,'%w') BETWEEN sch_wd_start AND sch_wd_end
            WHERE 
                vfl_status = 0 AND 
                chn_status = 1 AND
                vfl_start >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) AND 
                vfl_start <= DATE_ADD(NOW(), INTERVAL -11 MINUTE) AND 
                DATE_FORMAT(vfl_start,'%k') BETWEEN sch_hour_start AND sch_hour_end
            ORDER BY 
                vfl_id ASC
            ",
            'update'=>"
                UPDATE 
                    vsk_files
                SET 
                    vfl_status = 1
                WHERE 
                    vfl_status = 0 AND 
                    vfl_id IN (***ids***)
            "
        ),

        'crawler'=>array(),

    );
    return $sqls[$qName];
}
?>