<?php
require '../../fly2/fly3.php';
require 'config.php';
include_once('dither.php');

class EC3Renderer {
	var $colors;
	function imagecreatefromfile( $filename ) {
		switch ( strtolower( pathinfo( $filename, PATHINFO_EXTENSION ))) {
			case 'jpeg':
			case 'jpg':
				return imagecreatefromjpeg($filename);
			break;

			case 'png':
				return imagecreatefrompng($filename);
			break;

			case 'gif':
				return imagecreatefromgif($filename);
			break;

			default:
				return imagecreatefromjpeg($filename);
			break;
		}
	}
	function renderItem($im, $a, $data)
	{
		$cl = $this->colors;
		$thiscl = $a[color];
		
		if ($a[datasrc] && strcmp($a[datasrc], "데이터index")) {
			$key = str_replace("[", ".", $a[datasrc]);
			$key = str_replace("]", "", $key);
			$cnt = explode('.', $key)[1];
			// echo $key;
			$text = $data[$key];
			if (!$text)
			{
				$text = "";
				$a[imageUrl] = "";
			}
			//$text = $a[datasrc];
		} else {
			$text = $a[text];
		}
		
		$bgColor = "beds.".$cnt.".backgroundColor";
		if($data[$bgColor])	//cnt번째 병상에 backgroundColor 있는지 체크
		{
			$clr = explode('?', $data[$bgColor])[0];	//? 앞부분 (컬러이름)
			$param = explode('?', $data[$bgColor])[1];	//? 뒷부분 (? datasrc=info01)
			$val = explode('=', $param)[1];		//?datasrc="여기"
			
			if(!strcmp($a[datasrc], $val))	//datasrc랑 val이 같으면
				$a[backgroundColor] = $clr;	//배경색 설정
		}
		
		if (!$a[backgroundColor] || $a[backgroundColor] == 'transparent'){
			if($a[borderColor] != 'transparent')
				imagerectangle($im, $a[x], $a[y], $a[x]+$a[width], $a[y]+$a[height], $cl[$a[borderColor]]);
		}else{
			imagefilledrectangle($im, $a[x], $a[y], $a[x]+$a[width], $a[y]+$a[height], $cl[$a[backgroundColor]]);
			if($a[borderColor] != 'transparent')
				imagerectangle($im, $a[x], $a[y], $a[x]+$a[width], $a[y]+$a[height], $cl[$a[borderColor]]);
		}
		
		$imgurlcnt = "beds.".$cnt.".imageUrl";
		if($data[$imgurlcnt])	//cnt번째 병상에 imageUrl 있는지 체크
		{
			$imgurl = explode('?', $data[$imgurlcnt])[0];	//이미지 주소 (http://~.png 까지)
			$param = parse_url($data[$imgurlcnt], PHP_URL_QUERY);	//이미지 주소에서 ? 뒷부분 (? datasrc=info01)
			$val = explode('=', $param)[1];		//?datasrc="여기"
			
			if(!strcmp($a[datasrc], $val))	//datasrc랑 val이 같으면
			{
				$text = "";		//텍스트 안나오게
				$a[imageUrl] = "";	//기존 이미지 안나오게
				$img = $this->imagecreatefromfile($imgurl);	//이미지 그리기
				if($img) {
					imagecopyresized($im, $img, $a[x], $a[y], 0, 0, $a[width], $a[height], imagesx($img), imagesy($img));
				}
			}
		}
		
		if ($a[imageUrl]) {
			$img = $this->imagecreatefromfile($a[imageUrl]);
			if($img) {
				imagecopyresized($im, $img, $a[x], $a[y], 0, 0, $a[width], $a[height], imagesx($img), imagesy($img));
			}
		}
		
		if(!file_exists('view/font/'.$a['fontName'].'.ttf'))
			$a[fontName] = "NanumSquareB.ttf";
		if (!$a[fontName])
			$a[fontName] = "NanumSquareB.ttf";
		$font = "./view/font/$a[fontName]";
		$ftsize = $a[fontSize];
		$extent = imagettfbbox($ftsize, 0, $font, $text);
		
		while(($extent[4] - $extent[0])>$a[width])
		{
			$text = substr($text, 0, -1);
			$extent = imagettfbbox($ftsize, 0, $font, $text);
		}
		
		$x = $a[x];
		$y = $a[y]+$ftsize;
		if(!$a[hPadding])
			$a[hPadding] = 5;
		if(!$a[vPadding])
			$a[vPadding] = 5;
		switch($a[align]) {
		case 'center':
			$x += ($a[width] - $extent[2])/2;
			// console.log();
			break;
		case 'right':
			$x += ($a[width] - $extent[2])-$a[hPadding];
			break;
		default:
			$x += $a[hPadding];
			break;
		}
		switch($a[verticalAlign]){
		case 'middle':
			$y += ($a[height] - $ftsize)/2;
			break;
		case 'bottom':
			$y += ($a[height] - $ftsize);
			break;
		default:
			$y += $a[vPadding];
			break;
		}		
		
		$annoymous = "beds.".$cnt.".annoymous_color";
		if($data[$annoymous] && !strcmp(explode('.', $key)[2], "patient"))	//cnt번째 병상에 annoymous_color 있고, 지금 key가 patient(환자명)이면~
		{
			$image_width = 0;
			
			for($i=0; $i<mb_strlen($text); $i++)
			{
				$txt = mb_substr($text, $i, 1);
				
				if($i==1)
					imagettftext($im, $ftsize, 0, $x+$image_width, $y, $cl[$data[$annoymous]], $font, $txt);	
				else
					imagettftext($im, $ftsize, 0, $x+$image_width, $y, $cl[$thiscl], $font, $txt);
				
				$type_space = imagettfbbox($ftsize, 0, $font, $txt);
				$image_width += abs($type_space[4] - $type_space[0]);
			}
		}
		else
		{
			imagefttext($im, $ftsize, 0, $x, $y, $cl[$thiscl], $font, $text);
		}
	}
	function render($template, $data, $outputfilename)
	{
		$t = $template;
		$im = imagecreatetruecolor($t[width], $t[height]);
		$this->colors = array(
			red=>imagecolorallocate($im, 255, 0, 0),
			pink=>imagecolorallocate($im, 255, 120, 120),
			blue=>imagecolorallocate($im, 0, 0, 255),
			white=>imagecolorallocate($im, 255, 255, 255),			
			yellow=>imagecolorallocate($im, 255, 255, 0),				
			white=>imagecolorallocate($im, 255, 255, 255),
			black=>imagecolorallocate($im, 0, 0, 0),
			brown=>imagecolorallocate($im, 120, 60, 60),
		);
		$fn = "result/".$outputfilename;
		$cl = $this->colors;
		imagefilledrectangle($im, 0, 0, $t[width], $t[height], $cl[white]);
		
		foreach($t[items] as $item) {
			$this->renderItem($im, $item, $data);
		}
		$dt = new Dither();	
		$im= $dt->dither_kyt($im);
		//$im= $dt->dither_atkinson($im);
		//$im = $this->dither($im);
		$width = imagesx($im);
		$height = imagesy($im);		
		if($t[rotate] == 180){
			$rotateimg = imagerotate($im, $t[rotate], 0);
			imagepng($rotateimg, "./view/$fn");
			imagedestroy($im);
			imagedestroy($rotate);	
			return $fn;
		}else{
			if($width == 300 && $height == 400){
					$angle = 90;
					$rotate = imagerotate($im, $angle, 0);
					imagepng($rotate);
					imagedestroy($im, "./view/$fn");
					imagedestroy($rotate);
			}else if($width == 640 && $height == 384){
					$angle = 90;
					$rotate = imagerotate($im, $angle, 0);
					imagepng($rotate, "./view/$fn");
					imagedestroy($im);
					imagedestroy($rotate);
			}else if($width == 960 && $height == 640){
					$angle = 90;
					$rotate = imagerotate($im, $angle, 0);
					imagepng($rotate, "./view/$fn");
					imagedestroy($im);
					imagedestroy($rotate);
			}else if($width == 1600 && $height == 1200){
					$angle = 90;                           
					$rotate = imagerotate($im, $angle, 0);
					imagepng($rotate, "./view/$fn");
					imagedestroy($im);
					imagedestroy($rotate);
			}else{
				imagepng($im, "./view/$fn");
				imagedestroy($im);				
			}		
		}
	}
	function __construct()
	{
	}
	function onedim(&$r, $a, $prefix) {
		foreach($a as $k=>$v) {
			if($prefix == "")
				$newkey = $k;
			else
				$newkey = $prefix.".".$k;
			if (is_array($v)) {
				$this->onedim($r, $v, $newkey);
			} else {
				$r[$newkey] = $v;
			}
		}		
	}
	function serializeKeys($a) {
		$r = array();
		$this->onedim($r, $a, "");
		return $r;
	}
}

$app->action("index", function(&$view){
	$view = "index";
});

$app->action("api/get_etl", function(){
	$a = $_REQUEST;
	
	// $a[title] = "test";
	$title = "view/etl/".$a[title].".json";

	$data = file_get_contents($title);
	print_r($data);
});

$app->action("api/save", function(){	//서버 etl폴더에 템플릿 파일 저장
	$a = $_REQUEST;
	
	if(!is_dir("view/etl/"))
	{
		mkdir("view/etl/");
		chmod("view/etl/", 0777);
	}
	
	$file = fopen("view/etl/".$a[title].".json", 'w');
	fwrite($file, $a[data]);
	fclose($file);
});

$app->action("api/fetch_etl", function(){	//서버 etl 폴더 내 템플릿 파일 목록 가져오기
	$arr=array();
	$i=1;
	foreach(glob("view/etl/*.json") as $value)
	{ 
		$onlyName = substr($value,9,-5);
		$arr[] = $onlyName;
		$i++; 
	}
	reply_json($arr);
});

$app->action("api/delete", function(){
	$a = $_REQUEST;
	
	unlink("view/etl/".$a[title].".json");
});

$app->action("api/render", function(){
	$a = $_REQUEST;
	$data = $a[data];
	if (!is_array($a[data]))
		$data  = json_decode($a[data], true);
	$template = $a[template];
	if (!is_array($a[template]))
		$template = json_decode($a[template], true);
	
	if (!$data || !$template)
		throw new Exception("invalid data");
	
	$app = new EC3Renderer();
	$data = $app->serializeKeys($data);
	$app->render($template, $data, $a[outputfilename]);
	
	echo json_encode($a[outputfilename]);
});

$app->action("api/dl", function(){
	$a = $_REQUEST;
	if (!$a[data])
		die('no data');
	$data = json_decode($a[data], true);	
	header('Content-Description: File Transfer');
	//header('Content-Type: application/document');
	header('Content-Disposition: attachment; filename="'.$data[title].'.json"');
	header('Content-Transfer-Encoding: text');
	header('Expires: 0');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Pragma: public');
	//header('Content-Length: ' . count($data)); //Absolute URL
	ob_clean();
	flush();
	//readfile($file_url); //Absolute URL
	//exit();
	echo $a[data];
});

$app->action("api/import", function(){	//외부파일 import
	$a = $_REQUEST;
	$content = file_get_contents($_FILES['file']['tmp_name']);
	echo $content;
});

$app->action("api/import_etl", function(){	//서버 etl 폴더 내 템플릿 파일 import
	$a = $_REQUEST;
	$fn = "view/etl/".$a[templates].".json";
	$content = file_get_contents($fn);
	echo $content;
});

?>