<?php
namespace Engine\Debug\ParserCallTrace;

class ParserCallTraceDevelopmentDiskWriter extends ParserCallTraceDevelopment
{
	protected $output = null;
	protected $outputPath = null;
	protected $writtenBytes = 0;
	protected $writtenFiles = 0;

	public function __construct()
	{
		$file = str_replace(dirname($_SERVER['SCRIPT_NAME']).'/', '', $_SERVER['SCRIPT_NAME']);
		$this->startFile($file, '');

		$this->doPrint(sprintf(<<<BUTTONS
	<p class="float-right">
		<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#_SERVER" aria-expanded="false" aria-controls="_SERVER">_SERVER</button>
		<button class="btn btn-warning" type="button" data-toggle="collapse" data-target="#_GET" aria-expanded="false" aria-controls="_GET">_GET</button>
		<button class="btn btn-success" type="button" data-toggle="collapse" data-target="#_POST" aria-expanded="false" aria-controls="_POST">_POST</button>
	</p>
	<p class="clearfix">
		<div class="collapse alert alert-info clearfix" id="_SERVER">	<h3>_SERVER</h3>	<pre class="card card-body">%s</pre></div>
		<div class="collapse alert alert-warning clearfix" id="_GET">	<h3>_GET</h3>		<pre class="card card-body">%s</pre></div>
		<div class="collapse alert alert-success clearfix" id="_POST">	<h3>_POST</h3>		<pre class="card card-body">%s</pre></div>
	</p>
BUTTONS
, var_export($_SERVER, true), var_export($_GET, true), var_export($_POST, true)));

		parent::__construct();
	}

	public function __destruct()
	{
		if ($this->output) {
			$this->destroy();
			$this->doPrint(<<<HTML
</body>
</html>
HTML
);
			fclose($this->output);
			$this->output = null;
		}
	}

	protected function startFile($file, $fileSuffix)
	{
		$MODULE_REL_PATH = '';
		if (defined('MODULE_REL_PATH')) {
			$MODULE_REL_PATH = MODULE_REL_PATH;
		}
		$ts = microtime(true);
		$this->outputPath = realpath($MODULE_REL_PATH."../files/")."/ParserCallTraceDevelopmentDiskWriter/"
			. sprintf("%s.%s %s %s - %s %s %s%s.html",
				date("Ymd-His", $ts),
				str_replace("0.", "", sprintf("%0.4f", $ts - floor($ts))),
				mt_rand(1000, 9999),
				preg_replace("/[^a-zA-Z0-9_]/", '_', $_SERVER['REQUEST_METHOD']),
				preg_replace("/[^a-zA-Z0-9_]/", '_', $file),
				preg_replace("/[^a-zA-Z0-9_]/", '_', ($_GET['module']?:'null')),
				preg_replace("/[^a-zA-Z0-9_]/", '_', ($_GET['action']?:'null')),
				$fileSuffix
		);

		$this->output = fopen($this->outputPath, 'wb');
		if (!$this->output) {
			throw new \Exception(sprintf("[%s]Output file cannot be created", __METHOD__));
		}

		$this->doPrint(<<<HTML
<!DOCTYPE html>
<html class="" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
	<title>{$_SERVER['REQUEST_METHOD']} {$_SERVER['SCRIPT_NAME']}</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>

	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
</head>
<body>

HTML
);

	}

	protected function generateCSS()
	{
	return parent::generateCSS() . <<<CSS
<style type='text/css'>
	/* @see http://paletton.com/#uid=70h1f0ktgoQ2KuDhpoICHqmXgtE
			-> darker http://paletton.com/#uid=70h1f0ktw5H59fBjM6rK24EU2bK
	*/
	:root {
		font-size: 12px;
	}

	body {
		line-height: 1.1 !important;
	}
</style>
CSS;
	}

	protected function doPrint($str)
	{
		if ($this->output) {
			fwrite($this->output, $str);

			$this->writtenBytes+= strlen($str);

			if ($this->writtenBytes>(100*1024*1024)) {
				$this->writtenFiles++;
				$this->writtenBytes = 0;

				$file = str_replace(dirname($_SERVER['SCRIPT_NAME']).'/', '', $_SERVER['SCRIPT_NAME']);
				$this->startFile($file, sprintf(" (%05d)", $this->writtenFiles));

				$this->doPrint(sprintf(<<<HEADER
	<h1>continuation file #%d</h1>
HEADER
, $this->writtenFiles));
			}
		}
	}
}
