<?php

class TestCommand extends CConsoleCommand
{
    private  $days;

    private function mark($imagePath)
    {
        $image_info = getimagesize($imagePath);
        $imageType = $image_info[2];
        $create = null;
        $save = null;
        switch ($imageType) {
            case IMAGETYPE_JPEG:
                $create = 'imagecreatefromjpeg';
                $save = 'imagejpeg';
                break;
            case IMAGETYPE_GIF:
                $create = 'imagecreatefromgif';
                $save = 'imagegif';
                break;
            case IMAGETYPE_PNG:
                $create = 'imagecreatefrompng';
                $save = 'imagepng';
                break;
        }
        $path = realpath(Yii::getPathOfAlias('application') . '/../images/watermark.png');
        if (!isset($create)) return;
        $mark = imagecreatefrompng($path);
        $image = $create($imagePath);
        $x = 0;
        $y = 0;
        $w = round(imagesx($mark) * imagesx($image) / 800);
        $h = round(imagesy($mark) * imagesx($image) / 800);

        imagealphablending($image, true);
        imagesavealpha($image, true);

        imagecopyresampled($image, $mark, $x, $y, 0, 0, $w, $h, imagesx($mark), imagesy($mark));
        imagedestroy($mark);
        $save($image, $imagePath);
    }

    private function scanDir($dir)
    {
        $start = mktime(0, 0, 0, date('m'), date('d') - $this->days, date('Y'));
        $end = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

        //echo date('Y-m-d H:i:s', $start), "\n";
        //echo date('Y-m-d H:i:s', $end), "\n";

        foreach (scandir($dir) as $file) {
            if ($file == '.' || $file == '..' || substr($file,0,1) == '.') continue;
            $filename = $dir . '/' . $file;
            if (is_dir($filename)) {
                $this->scanDir($filename);
                continue;
            }
            $lastmod = filemtime($filename);
            // echo date('Y-m-d H:i:s', $lastmod), "\n";
            if ($lastmod >= $start && $lastmod < $end) {
                //$this->mark($filename);
                //@touch($filename, $lastmod);
				 echo date('Y-m-d H:i:s', $lastmod), "\n";
                 echo $filename, "\n";
            }
        }
    }

    public function actionAdd($days=1)
    {
        $this->days = (int)$days;
        $uploads = realpath(Yii::getPathOfAlias('application') . '/../uploads');
		
		$start = mktime(0, 0, 0, date('m'), date('d') - $this->days, date('Y'));
        $end = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

        echo date('Y-m-d H:i:s', $start), "\n";
        echo date('Y-m-d H:i:s', $end), "\n";

        $this->scanDir($uploads);
    }
}
