<?php

function getdupdatedbchannel($channelInfoNew) {
 foreach(array_keys($channelInfoNew) as $channelInfoKey) {
  if ($channelInfoNew[$channelInfoKey]["status"] == "ok" && $channelInfoNew[$channelInfoKey]["disabled"] == 2) return $channelInfoKey;
 } // foreach(array_keys($channelInfoNew) as $channelInfoKey) 
 return false;
} // function end 

function channelReaderJob() {
 global $globalsettings, $channelInfoNew, $isJobRunning, $bckStepArray;

 if (!array_key_exists("backgroundWorker", $isJobRunning)) $isJobRunning["backgroundWorker"]["isrunning"]=-1;

 if ($isJobRunning["backgroundWorker"]["isrunning"] == -1) {
  foreach(array_keys($channelInfoNew) as $channelInfoKey) {
   if ($channelInfoNew[$channelInfoKey]["status"] == "ok" && $channelInfoNew[$channelInfoKey]["mode"] != "a") {

    $updatedb=getdupdatedbchannel($channelInfoNew);
	if ($updatedb != false) $channelInfoKey=$updatedb; // overwrite channelInfoKey when found disabled: updatedb
    
    $insertlastrun=time()-(97*60*60);
    $sql="insert into bckworker values (".$channelInfoNew[$channelInfoKey]["chanid"].",'".pg_escape_string($globalsettings["db"]["pg_conn"], $channelInfoNew[$channelInfoKey]["name"])."',".$insertlastrun.",96)  on conflict (grpid) do nothing;"; // insert channel when not exists
    pg_query($globalsettings["db"]["pg_conn"], $sql);

    $sql="select lastrun, runafter from bckworker where grpid=".$channelInfoNew[$channelInfoKey]["chanid"];
    $result=pg_query($globalsettings["db"]["pg_conn"], $sql);

    while ($row = pg_fetch_array($result)) {
     $lastrun=$row['lastrun'];
     $runafter=$row['runafter'];
    } // while ($row = pg_fetch_array($result)) 
    $runafterInSeconds=$runafter * 60 * 60;
    $runNow=$lastrun+$runafterInSeconds; 

    if ($updatedb != false) $runNow=-1; // force updatedb 

    if (time() > $runNow) { 

     $sql="select tablename from pg_tables where schemaname = 'public' and tablename  = 'lock_".$channelInfoNew[$channelInfoKey]["chanid"]."';";
     $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
     if (pg_num_rows($result) !=0 ) {
      /* logger("job: backgroundworker - lock table exists, job not running(broken job): drop table lock_".$channelInfoNew[$channelInfoKey]["chanid"]);
      dropTable("lock_".$channelInfoNew[$channelInfoKey]["chanid"]); */
	  
	  $sql="select max(msgid) as maxid from lock_".$channelInfoNew[$channelInfoKey]["chanid"].";";
	  $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
	  if (pg_num_rows($result) !=0) {
       while ($row = pg_fetch_array($result)) {
        $maxid=$row["maxid"];
       } // if ($numrows != 0) 
      } // while ($row = pg_fetch_array
  
	  logger("job: channelReader - lock table[".$channelInfoNew[$channelInfoKey]["name"]."] exists, start job at message ".$maxid);
      $top_message=made("messages","getPeerDialogs", array("peers" => array($channelInfoNew[$channelInfoKey]["peerid"])))["dialogs"][0]["top_message"]; 
      logger("job: chnStepper - setup stepper for [".$channelInfoNew[$channelInfoKey]["name"]."] from ".$maxid." to ".$top_message);

      $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["limit"]=100;
      $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"] =$maxid;
      $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["to"]   =$top_message;
      $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["maxid"]=$top_message; // obsolet during top_message... 
	  
     } // if (pg_num_rows($result) !=0 ) 
		 
     pg_query($globalsettings["db"]["pg_conn"], pg_channelTableTemplate("chan_".$channelInfoNew[$channelInfoKey]["chanid"])); // create chan table when not exists
     pg_query($globalsettings["db"]["pg_conn"], pg_channelTableTemplate("lock_".$channelInfoNew[$channelInfoKey]["chanid"])); // create lock table when not exists

     $isJobRunning["backgroundWorker"]["isrunning"]=1;
     $isJobRunning["backgroundWorker"]["chanid"]=$channelInfoNew[$channelInfoKey]["chanid"];
     $isJobRunning["backgroundWorker"]["name"]=$channelInfoNew[$channelInfoKey]["name"];
     $isJobRunning["backgroundWorker"]["starttime"]=time();
     $isJobRunning["backgroundWorker"]["channelInfoKey"]=$channelInfoKey;
     logger("job: channelReader - start on [".$channelInfoNew[$channelInfoKey]["name"]."]"); 
     break;
    } // if (time() > $runNow)
   } // if ($channelInfoNew[$channelInfoKey]["status"] == "ok" && $channelInfoNew[$channelInfoKey]["mode"] != "a") 
  } // foreach(array_keys($channelInfoNew) as $k) 

 } else {
  $channelInfoKey=$isJobRunning["backgroundWorker"]["channelInfoKey"];
  $stepsleft=round(($bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["to"] - $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"]) / $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]['limit']);

  logger("job: channelReader - work on [".$channelInfoNew[$channelInfoKey]["name"]."], current msg: ".$bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"]." to goal: ".$bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["to"]);
 } // if ($isJobRunning["backgroundWorker"]["isrunning"] == -1) - else
 return;
} // function end