<?php
/**
 * 主服务linux/unix版本，启动其他相关所有服务，并监控服务状态和停止及重启服务
 * 
 * 
 */
ini_set("display_errors", 0);
error_reporting(E_ALL & ~E_NOTICE);
use Workerman\Worker;
use Workerman\Protocols\Http\Response;
use Workerman\Lib\Timer;
use Workerman\Connection\AsyncTcpConnection;

define('DS', DIRECTORY_SEPARATOR);
define('CURRENT_OS', strtoupper(substr(php_uname(),0,3)));
if(CURRENT_OS == 'WIN'){
	exit('当前系统为WINDOWS，请执行win.php');
}
$dir = str_replace("\\","/", __FILE__);
defined('ROOT_PATH') or define('ROOT_PATH', dirname($dir) . DS);


require_once './workerman/Autoloader.php';

global $web;
$web = new Worker('http://0.0.0.0:7778');
$web->count = 4;
$web->name = 'webservice';
$web->onWorkerStart = function($task)
{
	
};
$web->onMessage = function($connection, $request)
{
	$file = dirname(ROOT_PATH) . DS .'public'.DS.'img'.DS.'calendar'.DS;
	ini_set("display_errors", 0);
	error_reporting(E_ERROR);
	$path = $request->path();
	$query = $request->queryString();
	parse_str($query,$query_arr);
	if($path == '' || $path=='/'){
		$data = json_encode(['code'=>200,'msg'=>'unknow actions.']);
		$response = new Response(200,[],$data);
		$response->header('Content-Type', 'application/json');
		$connection->close($response);
	}else{
		if(substr($path, 0,1) == '/'){
			$path = substr($path, 1);
		}
		if(strpos($path,'/') !== false){
			$path = str_replace('/', DS, $path);
		}
		$pathInfo = explode(DS, $path);
		switch ($pathInfo[0]) {
			case 'histogram':
				# 生成直方图方法
				unset($pathInfo[0]);
				$file .= implode(DS, $pathInfo);
				$size = array(
					'width' => 1024,
					'height' => 400,
				);
				if(!file_exists($file)){
					$data = json_encode(['code'=>200,'msg'=>'unsupport actions.']);
					$response = new Response(200,[],$data);
					$response->header('Content-Type', 'application/json');
					$connection->close($response);
				}else{
					$type = $query_arr['type'];
					if($type){
						$type = explode(',', $type);
					}else{
						$type = ['r','g','b'];
					}



					$fileName = basename($file);
					$fileHash = md5_file($file);
					$fileDir = dirname($file);

					$cacheExt = 'HC-'.implode('', $type).'.'.$fileName;

					$cacheFile = $fileDir.DS.$fileHash.'.'.$cacheExt;
					if(file_exists($cacheFile)){
						$content = file_get_contents($cacheFile);
						$response = new Response(200,[],$content);
						$response->withProtocolVersion('1.0');
						$response->header('Content-Type', 'image/png');
						$response->header('Connection','close');
						$response->header('Accept-Ranges','bytes');
						$response->header('Cache-Control','max-age=8640000');
						$connection->close($response);
						return ;
					}else{
						//清理掉可能之前留下的文件
						$list = scandir($fileDir);
						foreach ($list as $dir) {
							if(substr($dir,0,1) == '.' || $dir == 'Thumbs.db'){
				            	// 过虑隐藏文件或.开头的文件
				                continue;
				            }
				            if(is_file($fileDir.DS.$dir) && strpos($dir,$cacheExt)){
				            	unlink($fileDir.DS.$dir);
				            	// echo 'del:'.$fileDir.DS.$dir;
				            }
						}
					}
					$image = new \Imagick($file);
					$histogram = array_fill_keys(range(0, 255), 0);
					
					foreach ($image->getImageHistogram() as $pixel) {
						$rgb = $pixel->getColor();
						if(in_array('r', $type)){
							$histogram[$rgb['r']] += $pixel->getColorCount();
						}
						if(in_array('g', $type)){
							$histogram[$rgb['g']] += $pixel->getColorCount();
						}
						if(in_array('b', $type)){
							$histogram[$rgb['b']] += $pixel->getColorCount();
						}
					}
					$max = max($histogram);
					$threshold = ($image->getImageWidth() * $image->getImageHeight()) / 256 * 12;
					if ($max > $threshold) {
					$max = $threshold;
					}
					\Imagick::setResourceLimit(\Imagick::RESOURCETYPE_MEMORY,102400000);
					\Imagick::setResourceLimit(\Imagick::RESOURCETYPE_MAP,102400000);
					$image = new \Imagick();
					$draw = new \ImagickDraw();
					$image->newImage($size['width'], $size['height'], 'white');
					foreach ($histogram as $x => $count) {
						if ($count == 0) {
							continue;
						}
						$draw->setStrokeColor('black');
						$height = min($count, $max) / $max * $size['height'];
						$xx = $x *4;
						$xxx = ($x +1) * 4 - 1;
						for ($i=$xx; $i <= $xxx; $i++) { 
							$draw->line($i, $size['height'], $i, $size['height'] - $height);
						}
						
						$image->drawImage($draw);
						$draw->clear();
					}
					$image->setImageFormat('png');

					// $image->writeImage('histogram.png');
					// header("Content-Type: image/png");
					$content = $image->getimageblob();
					file_put_contents($cacheFile, $content);
					// echo \Imagick::getResourceLimit(\Imagick::RESOURCETYPE_MEMORY);
					$a = $image->clear();
					$b = $image->destroy();
					$c = $draw->destroy();
					unset($image,$draw,$histogram);
					$response = new Response(200,[],$content);
					$response->withProtocolVersion('1.0');
					$response->header('Content-Type', 'image/png');
					$response->header('Connection','close');
					$response->header('Accept-Ranges','bytes');
					$response->header('Cache-Control','max-age=8640000');
					$connection->close($response);
				}
				break;
			default:
				$data = json_encode(['code'=>200,'msg'=>'unsupport actions.']);
				$response = new Response(200,[],$data);
				$response->header('Content-Type', 'application/json');
				$connection->close($response);
				break;
		}
	}
	
};

// 运行worker
Worker::runAll();