<?php
namespace SPAATG\Model;

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

class StatsModel
{

  // Below are counted and saved in settings
  //protected $totalOptimized; // combined filesize of optimized images
  //protected $totalOriginal;  // combined filesize of original images

  // There are gotten via SQL and saved in stats
  //protected $totalImages;
  //protected $totalThumbnails

  protected $lastUpdate;
  protected $path = array();

  protected $currentStat;  // used for chaining it.

  protected $refreshStatTime;


  // Commented out stats were dropped.
  // Note: the difference in items / images including thumbs and the counts don't . This is due to technical difference in acquiring the data.
    protected $defaults = array(
      'media' => array('items' => -1, // total optimized media items found
                       'images' => -1, // total optimized images (+thumbs) found
                       'thumbs' => -1, // Optimized thumbs - SQL does thumbs, but queue doesn't. (imprecise query)
                       'itemsTotal' => -1, // Total items in media  ( sql )
                       'thumbsTotal' => -1, // Total thumbs in media ( sql ) - imprecise query
											 'isLimited' => false,
                  /*     'lossy' => 0, // processed x compression
                       'lossy_thumbs' => 0, // main / thumbs
                       'lossless' => 0, // main /thumbs
                       'lossless_thumbs' => 0,
                       'glossy' => 0,
                       'glossy_thumbs' => 0, */
      ),
      'custom' => array('items' => -1, // total optimized custom items
                        'images' => -1, // total optimized custom images
                        'itemsTotal' => -1,

                      /*  'lossy' => 0, // process x compression
                        'lossless' => 0,
                        'glossy' => 0, */
      ),
      'period' => array('months' =>  // amount of images compressed in x month
                    array('1' => -1,  /// count x months ago what was done.
                        '2' => -1,
                        '3' => -1,
                        '4' => -1,
                    ),
      ),
      'total' => array('items' => -1,
                       'images' => -1,
                       'thumbs' => -1,
                       'itemsTotal' => -1,
                       'thumbsTotal' => -1,
                     ),

    /*  'total' => array('items' => 0,  // total items found
                       'images' => 0, // total images found
      ), */
  );

  protected $stats;  // loaded as defaults, or from dbase.

  public function __construct()
  {
      $this->refreshStatTime = apply_filters('spaatg/statistics/refresh', WEEK_IN_SECONDS);
      $this->load();
  }

  public function load()
  {
    $settings = \wpSPAATG()->settings();

    $stats = $settings->currentStats;
		if (! is_array($stats))
		{
			 $stats = $this->defaults;
		}

		$stats = array_filter($stats);

    // Legacy. Stats from < 5.0 are loaded somehow. Don't load them.
    if (isset($stats['APIKeyValid']))
		{
      $stats = $this->defaults;
		}

		$stats = array_merge($this->defaults, $stats); // merge like args to ensure full structure present.

    $this->lastUpdate = (isset($stats['time'])) ? $stats['time'] : 0;

    if ( ($this->lastUpdate + $this->refreshStatTime) >= time())
    {
       $this->stats = $stats;
    }
    else
		{
      $this->stats = $this->defaults;
		}

  }

  public function save()
  {
     $settings = \wpSPAATG()->settings();
     $stats = $this->stats;
     $stats['time'] = time();
     $settings->currentStats = $stats;
  }

  public function reset()
  {
      $this->stats = $this->defaults;
			\wpSPAATG()->settings()->deleteOption('currentStats');

  //    $this->save();
  }

  // @todo This is not functional
  public function add($stat)
  {
     if (property_exists($stat, 'images'))
         $this->stats[$stat->type]['images'] += $stat->images;
     if (property_exists($stat, 'items'))
        $this->stats[$stat->type]['items'] += $stat->items;


  }

  public function get($name)
  {
      if (property_exists($this, $name))
         return $this->$name;
      else
        return null;
  }

  public function getStat($type)
  {
      $this->currentStat = null;
      if (isset($this->stats[$type]))
      {
         $stat = $this->stats[$type];

         $this->currentStat = $this->checkInt($stat);
         $this->path = [$type];
      }

      return $this;
  }

  public function grab($data)
  {
     if (is_null($this->currentStat))
          return null;

       if (is_array($this->currentStat) && array_key_exists($data, $this->currentStat))
       {
          $this->currentStat = $this->checkInt($this->currentStat[$data]);
          $this->path[] = $data;
       }


       if (! is_array($this->currentStat))
       {

         if ($this->currentStat === -1)
         {
            $this->currentStat = $this->checkInt($this->fetchStatdata());  // if -1 stat might not be loaded, load.
         }

        return $this->currentStat;
       }
       else
			 {
        return $this;
			 }
  }

  private function fetchStatData()
  {
      $path = $this->path;
      $data = -1;

      if ($path[0] == 'period' && $path[1] == 'months' && isset($path[2]))
      {
          $month = $path[2];

          $data = $this->countMonthlyOptimized(intval($month));

          if ($data >= 0)
          {
            $this->stats['period']['months'][$month] = $data;
            $this->save();
          }

      }
      if ($path[0] == 'media')
      {
          switch($path[1])
          {
            case 'items':
              $data = $this->countMediaItems(['optimizedOnly' => true]);
            break;
            case 'thumbs': // unrealiable if certain thumbs are not optimized, but the main image is.
              $data = $this->countMediaThumbnails(['optimizedOnly' => true]);
            break;
            case 'images':
              $data = $this->getStat('media')->grab('items') + $this->getStat('media')->grab('thumbs');
            break;
            case 'itemsTotal':
              $data = $this->countMediaItems();
            break;
            case 'thumbsTotal':
               $data = $this->countMediaThumbnails();
            break;
						case 'isLimited':
								$data = $this->stats['media']['isLimited'];
						break;
          }

          if ($data >= 0)
          {
						 if (is_numeric($data))
						 {
							  $data = max($data, 0);
						 }
             $this->stats['media'][$path[1]] = $data; // never allow any data below zero.
             $this->save();
          }
      }


      if ($path[0] == 'custom')
      {
          switch($path[1])
          {
             case 'items':
                $data = $this->customItems(['optimizedOnly' => true]);
             break;
             case 'itemsTotal':
                $data = $this->customItems();
             break;
          }

          if ($data >= 0)
          {
             $this->stats['custom'][$path[1]] = $data;
             $this->save();
          }
      }

      if ($path[0] == 'total')
      {
         switch($path[1])
         {

            case 'items':
              $media = $this->getStat('media')->grab('items');
              $custom = $this->getStat('custom')->grab('items');
              $data = $media + $custom;
            break;
            case 'images':
              $media = $this->getStat('media')->grab('images');
              $custom = $this->getStat('custom')->grab('items'); // items == images
              $data = $media + $custom;
            break;
            case 'thumbs':
               $data = $this->getStat('media')->grab('thumbs');
            break;
            case 'itemsTotal':
                $media = $this->getStat('media')->grab('itemsTotal');
                $custom = $this->getStat('custom')->grab('itemsTotal');
                $data = $media + $custom;
            break;
            case 'thumbsTotal':
                $data = $this->getStat('media')->grab('thumbsTotal');
            break;

         }
         if ($data >= 0)
         {
            $this->stats['total'][$path[1]] = $data;
            $this->save();
         }
      }

      return $data;

  }

  private function checkInt($var)
  {
    if (is_numeric($var) && gettype($var) !== 'integer')
    {
       $var = intval($var);
    }
    return $var;

  }


  // suboptimal over full stats implementation, but faster.
	  private function countMediaThumbnails($args = array())
	  {
	     return 0;
	  }

  private function countMediaItems($args = array())
  {
	      $defaults = array(
	        'optimizedOnly' => false,
	      );

	      $args = wp_parse_args($args,$defaults);

	      if ($args['optimizedOnly'] == true)
	      {
	        return AiDataModel::countGeneratedMediaItems();
	      }
				else {
					return AiDataModel::countCandidateMediaItems();
				}
	  }

	  private function countMonthlyOptimized($monthsAgo = 1)
	  {
	     return AiDataModel::countGeneratedMediaItems(['months_ago' => $monthsAgo]);
	  }

  private function customItems($args = array())
  {
       return 0;
  }


} // class
