<?php

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

 if (!array_key_exists("backgroundWorker", $isJobRunning)) return; // no job on isJobRunning
 if ($isJobRunning["backgroundWorker"]["isrunning"] == -1) return; // no job running
 
 $channelInfoKey=$isJobRunning["backgroundWorker"]["channelInfoKey"];

 if (!array_key_exists($channelInfoNew[$channelInfoKey]["peerid"], $bckStepArray)) {
  $sql="select max(msgid) as maxid from chan_".$channelInfoNew[$channelInfoKey]["chanid"];
  $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
  while ($row = pg_fetch_array($result)) $maxid=$row['maxid'];
  if (!isset($maxid)) $maxid=0;

  $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 100 to ".$top_message);

  $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["limit"]=100;
  $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"] =100;
  $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["to"]   =$top_message;
  $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["maxid"]=$maxid; // obsolet during top_message... 

 } // if (!array_key_exists($channelInfoNew[$channelInfoKey]["peerid"], $bckStepArray))

 $from=$bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"];
 while (true) { // find first message in chan, when admin have massive messages deleted
  $out=made("messages","getHistory", array("peer" => $channelInfoNew[$channelInfoKey]["peerid"], "offset_id" => $from, "limit" => $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["limit"]));
  if (count($out['chats']) != 0) { $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"]=$from; break; }
  $from=100+$from; 
  logger("job: chnStepper - no messages found ".$from." - [".$channelInfoNew[$channelInfoKey]["name"]."]");
  sleep(1);
 } // while (true)

  if ($from != $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["to"]) {
   if ($from >= $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["to"]) { 
    $from=$bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["to"]; 
    $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"]=$from;
   } else $bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"]=$bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["from"]+$bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["limit"];

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

   insertData(parseData($out), $channelInfoKey, 1, 1); // $donotsync=1; $locktable=1;
  } else { // parse messages done
   logger("job: chnStepper - channelReader done @ [".$channelInfoNew[$channelInfoKey]["name"]."]");

    $sql="delete from chan_".$channelInfoNew[$channelInfoKey]["chanid"]." t1 where t1.msgid < ".$bckStepArray[$channelInfoNew[$channelInfoKey]["peerid"]]["maxid"]." and not exists (select msgid from lock_".$channelInfoNew[$channelInfoKey]["chanid"]." t2 where t1.msgid = t2.msgid and t1.type = t2.type and t1.size = t2.size)";
    pg_query($globalsettings["db"]["pg_conn"], $sql);

    $sql="insert into chan_".$channelInfoNew[$channelInfoKey]["chanid"]." select * from lock_".$channelInfoNew[$channelInfoKey]["chanid"]." on conflict (msgid) do nothing;";
    pg_query($globalsettings["db"]["pg_conn"], $sql);
    
    dropTable("lock_".$channelInfoNew[$channelInfoKey]["chanid"]); 

   // bckWorker table
   $sql="update bckworker set lastrun=".$isJobRunning["backgroundWorker"]["starttime"]." where grpid=".$channelInfoNew[$channelInfoKey]["chanid"];
   pg_query($globalsettings["db"]["pg_conn"], $sql);

   // set backgroundworker to not running
   $isJobRunning["backgroundWorker"]["isrunning"]=-1;

   // check if disabled: updatedb - reset disabled to false & rewrite config
   if ($channelInfoNew[$channelInfoKey]["disabled"] == 2) {
	$channelInfoNew[$channelInfoKey]["disabled"]=-1;
	$channelInfoNew[$channelInfoKey]["status"]="ok";
	$channelInfoNew[$channelInfoKey]["info"]="ready";
	writeChannelConfig($channelInfoNew);
	loadChannelConfig(true);
	writeChannelConfig($channelInfoNew);    	
   } // if ($channelInfoNew[$channelInfoKey]["disabled"] == 2) 	 

  } // else if ($from != $bckStepArray[$peerID]["to"])

 return;
} // function end