<?php

require_once 'globals.php';


class deleteOldImagesCommand extends CConsoleCommand
{

    function RemoveEmptySubFolders($path)
    {
        $empty=true;
        foreach (glob($path.DIRECTORY_SEPARATOR."*") as $file)
        {
            $empty &= is_dir($file) && RemoveEmptySubFolders($file);
        }
        return $empty && rmdir($path);
    }
    
	
    public function deleteImagesOnFileSystem($days, $tillDays)
	{
		$offset = 0;
		
		$curdb  = explode('=', Yii::app()->db->connectionString);
		$dbName =  $curdb[2];
		
		echo "\ndb=$dbName";

		echo "\nd -> parse STORICOTABLE";
		
		
		$nowTime = new DateTime();

		$lastTime = clone $nowTime;

		
		$lastTime->sub(new DateInterval("P".$days."D"));
		
		$condition = "t.StartTime < '". $lastTime->format("Y-m-d H:i:s") ."'";
		
		if($tillDays > 0)
		{
		    $toTime =  clone $nowTime;
		    $toTime->sub(new DateInterval("P".$tillDays."D"));
		    
		    $condition = "t.StartTime < '". $lastTime->format("Y-m-d H:i:s") ."' and t.StartTime >= '".$toTime->format("Y-m-d H:i:s")."'";
		}
		
		echo "\ncondition: ". $condition;
		
		$step = 1000;
		
		$offset = 0;
		
		do
		{
		    $resEv = Event::model()->findAll(array('condition'=>$condition,  'order' => 't.StartTime', 'limit' => $step, 'offset' => $offset ));
				
			$count = count($resEv);
				
			if($count <= 0)
				break;
				
			$offset += $count;
	
			echo "\n export Images: ".$count." / ".$offset;
			echo "\n";
	
			foreach($resEv as $ev)
			{
			    echo $ev->ID."_";
				
								
				foreach($ev->photosAll() as $media)
				{
                    echo "check blob";				    
			    
				    if(isEmpty($media->BlobFileName))
				    {
				        echo " -> no file \n";
				        continue;
				    }
				    
                    $filename = $media->getPath();
                    echo " -> delete file: ".$filename."\n";
                    
                    if(file_exists($filename))
                        unlink($filename);
				}

				foreach($ev->photosAll() as $media)
				{
				    echo "\n delete from teb_table where ID=".$media->ID;
				    Yii::app()->db->createCommand("delete from teb_table where ID=".$media->ID)->execute();
				}
				
				$bfn = pathCombine(Yii::app()->params['photoBasePath'], $ev->BlobFileName);
				if (fileExists($bfn))
				    unlink($bfn);

				
				Yii::app()->db->createCommand("update storicotable set blobfilename = '' where ID=".$ev->ID)->execute();
			
			}
			
			$offset += $step;
		}
		while($count >= 0);
		
	}
	

		
	
	public function run($args)
	{
		echo hello;
		
		echo "\n######################################################################";
		echo "\n##                                                                  ##";
		echo "\n##                     EVENTSERVER IMAGE HOUSEKEEPER                ##";
		echo "\n##                                                                  ##";
		echo "\n######################################################################";
		echo "\n";
		echo "\n";
		
		
		
		$options = $this->resolveRequest($args);
		
		var_dump($options);

		echo count($args) ;
		echo array_search('/?', $args) ;
		
		if(count($args) <= 0 || array_search('/?', $args) != FALSE || array_search('-?', $args) != FALSE)
		{
			
			if(count($args) <= 0)
				echo "\n Please specify one or more arguments!";
			
			echo "\n";
			echo "\n -saveDays=<num of days>               delete images startimg from now - (num of days)";
			echo "\n -tillDays=<num of days>               delete images till now - (num of days). unspecifiedfor all";
				
			echo "\n";
			echo "\n";
				
			
			return 0;
		}
		

		
        
		
		$days = intval($options[1]["saveDays"]);

		
		
		echo "\ndelete older than ".$days." days\n";
		
		$tillDays = 0;
		
		if(array_key_exists("tillDays", $options[1]))
		{
		  $tillDays = intval($options[1]["tillDays"]);
		  echo "\nuntil ".$tillDays." days\n";
		}
			
		//return 0;
		
		Yii::app()->db->schema->refresh();
		

		echo "\n##################################################################";
		echo "\n delete Images";
		echo "\n##################################################################";
	
		echo "\ndelete images...";
		self::deleteImagesOnFileSystem($days, $tillDays);
			
		echo "\ndelete empty folders...";
		self::RemoveEmptySubFolders(Yii::app()->params['photoBasePath']);
		echo "\n done";
		
		return 0;
		
	}
	
}
?>