<?php
    $QueueStatement = $RUNTIME['PDO']->prepare("SELECT * FROM queue WHERE QueueType = 'addRegion'");
    $QueueStatement->execute(array()); 

    while($row = $QueueStatement->fetch())
    {
        $queueData = json_decode($row['QueueData']);
        $REGIONDATA = array();
        
        if(ping($queueData->Hostname, $queueData->Port))
        {
            $stats = getRegionStats($queueData->Hostname.":".$queueData->Port);
            
            if($stats != false)
            {
                if($stats->RegionName != $queueData->RegionName)
                    break;

                if(!isset($stats->RootAg))
                    break;

                if(!isset($stats->Version))
                    break;

                $REGIONDATA['Avatare'] = $stats->RootAg;
                $REGIONDATA['Version'] = trim(substr(str_replace("  ", "", $stats->Version), 0, 16));
                $REGIONDATA['MAP'] = "http://".$queueData->Hostname.":".$queueData->Port."/index.php?method=regionImage".trim(str_replace("-", "", $queueData->UUID));
                
                if(isset($queueData->Image))
                    $REGIONDATA['Image'] = $queueData->Image;

                if(!isset($queueData->Image))
                    $REGIONDATA['Image'] = guidv4();

                if(isset($stats->RootAg) && isset($stats->NPCAg))
                    $REGIONDATA['Avatare'] = $stats->RootAg - $stats->NPCAg;

                $QueueStatement = $RUNTIME['PDO']->prepare("REPLACE INTO onlinetimes VALUES (?, ?, ?)");
                $QueueStatement->execute(array($queueData->UUID, time(), $REGIONDATA['Avatare'])); 

                $QueueStatement = $RUNTIME['PDO']->prepare("REPLACE INTO regions VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $QueueStatement->execute(array($queueData->RegionName, $queueData->UUID, $queueData->GridName, $REGIONDATA['Image'], "00000000-0000-0000-0000-000000000000", $queueData->Hostname, $queueData->Port, $REGIONDATA['Version'])); 

                if(isset($queueData->Image))
                {
                    $QueueStatement = $RUNTIME['PDO']->prepare("INSERT INTO queue VALUES (?, ?, ?)");
                    $QueueStatement->execute(array(guidv4(), "assetImageDownload", json_encode(array("RegionUUID" => $queueData->UUID, "HomeURL" => @$queueData->Image, "TargetAssetUUID" => $queueData->Image)))); 
                }

                if(!isset($queueData->Image))
                {
                    $QueueStatement = $RUNTIME['PDO']->prepare("INSERT INTO queue VALUES (?, ?, ?)");
                    $QueueStatement->execute(array(guidv4(), "regionImageDownload", json_encode(array("RegionUUID" => $queueData->UUID, "URL" => $REGIONDATA['MAP'], "TargetAssetUUID" => $REGIONDATA['Image'])))); 
                }

            }
        }

        $removeQueueStatement = $RUNTIME['PDO']->prepare("DELETE FROM queue WHERE QueueID = ?");
        $removeQueueStatement->execute(array($row['QueueID'])); 
    }

?>