<?php
namespace SPAATG\Controller;

if ( ! defined( 'ABSPATH' ) ) {
 exit; // Exit if accessed directly.
}

use SPAATG\ShortPixelLogger\ShortPixelLogger as Log;

class CronController
{

  private static $instance;

  protected $cron_options = array();
  protected $cron_hooks = array();

  protected $background_is_active = false;

  public function __construct()
  {
     $this->checkActive();
     // Important that the schedules filter always goes for unscheduling, even when non-active.
     add_filter( 'cron_schedules', array($this,'cron_schedules') );

     $this->init();
     $this->removeLegacyCron();
     if (false === wp_doing_ajax())
     {
       // No need to load anything
       if (false === $this->background_is_active)
       {
          $this->bulkRemoveAll();
       }
       else {
          $this->bulk_scheduler();
       }

     }

  }

  public static function getInstance()
  {
     if ( is_null(self::$instance))
        self::$instance = new static();

    return self::$instance;
  }

  public function cron_schedules($schedules)
  {
        $schedules['spaatg_interval'] = array(
	          'interval' => apply_filters('spaatg/cron/interval', 60),
          'display' => __('ShortPixel cron interval', 'shortpixel-ai-alt-text-generator')
        );

        $schedules['spaatg_interval_30min'] = array(
	          'interval' => apply_filters('spaatg/cron/interval', 30 * MINUTE_IN_SECONDS),
          'display' => __('ShortPixel 30 min interval', 'shortpixel-ai-alt-text-generator')
        );

        return $schedules;
  }

  protected function init()
  {

      // Defaults
      $background_crons = array(
          'single' => array(
              'cron_name' => 'spaatg-single-cron',
              'bulk' => false,

          ),
          'bulk' => array(
            'cron_name' => 'spaatg-bulk-cron',
            'bulk' => true,
          ),
      );

      foreach($background_crons as $name => $options)
      {
         add_action($options['cron_name'], array(AdminController::getInstance(), 'processCronHook'));
      }

      $this->cron_options = $background_crons;
  }

  protected function checkActive()
  {
      $this->background_is_active = false;
  }


  public function checkNewJobs()
  {
       if ( true === $this->background_is_active)
       {
          $this->bulk_scheduler();
       }
  }

  public function onDeactivate()
  {
      $this->bulkRemoveAll();
      $this->removeLegacyCron();
  }

  protected function bulk_scheduler()
  {
         foreach($this->cron_options as $type => $options)
         {
            $name = $options['cron_name'];
            $args = [0 => [
                  'bulk' => $options['bulk']]
              ];

            if ( false === wp_next_scheduled($name, $args))
            {
              $this->bulkScheduleEvent($type, $options, $args);
            }
            else  {
              // check if still items, or how do we do this (@todo)
              $this->bulkCheckevent($type, $options, $args);
            }
         }
  }

  protected function removeLegacyCron()
  {
      $this->unscheduleEvent('spaatg-refresh-dir', ['args' => ['amount' => 10]]);
      $this->unscheduleEvent('spaatg-refresh-dir', [0 => ['amount' => 10]]);
      $this->unscheduleEvent('spaatg-single-cron', array('bulk' => false));
      $this->unscheduleEvent('spaatg-bulk-cron', array('bulk' => true));
  }

  protected function unscheduleEvent($name, $args)
  {
      $timestamp = wp_next_scheduled($name, $args);
      if (false !== $timestamp)
      {
          wp_unschedule_event($timestamp, $name, $args);
      }
  }

  protected function bulkScheduleEvent($queue_type, $options, $args)
  {
      $data = $this->getQueueData($queue_type);

      $items = $data->total->stats->awaiting;
      $is_running = $data->total->stats->is_running;


      // Only queue must have a run command, nothing else.
       if ('bulk' === $queue_type && false === $is_running)
       {
          return false; // no queues running
       }

       if ($items  > 0)
       {
          wp_schedule_event(time(), 'spaatg_interval', $options['cron_name'], $args);
       }

  }

  protected function bulkRemoveAll()
  {
    foreach($this->cron_options as $type => $options)
    {
       $name = $options['cron_name'];
       $args = [0 => [
             'bulk' => $options['bulk']]
         ];

       if (false !== wp_next_scheduled ($name, $args))
       {
         $bool = wp_unschedule_event(wp_next_scheduled($name, $args), $name, $args);
       }
    }
  }

  protected function bulkCheckEvent($queue_type, $options, $args)
  {
      $data = $this->getQueueData($queue_type);


      if ($data->total->stats->awaiting == 0)
      {
         $name = $options['cron_name'];
         $bool = wp_unschedule_event(wp_next_scheduled($name, $args), $name, $args);
      }
  }

  // This could be transferred to getStartUpData instead.
  private function getQueueData($queue_type)
  {
      if ('bulk' === $queue_type)
      {
         $args['is_bulk'] = true; 
      }
      else
      {
        $args['is_bulk'] = false;
      }


      $queueController = new QueueController($args);
      return $queueController->getStartUpData();


  }


} // class
