<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/


class TB_Server_Core_JobProcessor
{
    private $nowDt;

    public function __construct()
    {
        $this->nowDt = new DateTime( 'now',  new \DateTimeZone( "UTC" )  );
    }

    public function process()
    {
        $jobs = TB_Shared_Ent_TeamData_Job::getAllReadyAndExpiredJobs( $this->nowDt );
        TB_Shared_Ent_TeamData_Job::markAllForProcessing( $this->nowDt );

        /** @var TB_Shared_Ent_TeamData_Job $job */
        /*
        foreach( $jobs as $job )
        {
            try
            {
                // First - mark all jobs as being processed
                $job->job_status = TB_Shared_Ent_TeamData_Job::JOB_STATUS_PROCESSING;
                $job->save();
            }
            catch( \Exception $e )
            {
                // Fail silently
            }
        }
        */

        /** @var TB_Shared_Ent_TeamData_Job $job */
        foreach ( $jobs as $job )
        {
            // Process
            try
            {
                $jobClass = 'TB_Server_Job_' . ucfirst( $job->job_name );
                /** @var TB_Server_Job_Base $jobInstance */
                $jobInstance = new $jobClass( $job );
                if ( $jobInstance instanceof TB_Server_Job_Base )
                {
                    $jobInstance->execute();
                    $jobInstance->onDone();
                }
                else
                {
                    $job->delete();
                }
            }
            catch ( \Exception $e )
            {
                TB_Server_Utils_Log::get()->log( $e );
                try
                {
                    $job->delete();
                }
                catch( \Exception $ee )
                {
                    TB_Server_Utils_Log::get()->log( $ee );
                }
            }
        }
    }
}