<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

if (empty($lines)) {
	print sly_Helper_Message::info('Die Datei ist leer.');
	return;
}

$table     = new sly_Table('log');
$firstLine = reset($lines);

foreach ($firstLine as $colName => $value) {
	$table->addColumn(new sly_Table_Column($colName, '', '', array('class' => 'group-'.$colName)));
}

$table->openBuffer();

foreach ($lines as $line) {
	?>
	<tr class="log-line">
		<?php foreach ($line as $key => $value): ?>
		<td class="log-element group-<?php print $key ?>"><?php print sly_html($value) ?></td>
		<?php endforeach ?>
	</tr>
	<?php
}

$table->closeBuffer();
print $table->render();

$base = sly_Util_AddOn::assetBaseUri('webvariants/developer-utils');

if (!$short && count($lines) === 50) {
	?>
	<p class="nav more"><a href="#">mehr anzeigen</a></p>
	<p class="nav loading"><img src="<?php print $base ?>images/log-loading.gif" alt="" title="Lade..." /></p>

	<script type="text/javascript">
	jQuery(function($) {
		var get    = '<?php print urlencode(sly_get('get', 'string')) ?>';
		var offset = 0;

		$('.more').click(function() {
			$('.nav').toggle();
			offset += 50;

			$.ajax({
				type:     'GET',
				cache:    false,
				url:      'index.php?page=devutilslogviewer&func=ajax&get=' + get + '&offset=' + offset,
				dataType: 'json',
				success:  function(data) {
					if (data.length === 0) {
						$('.nav').hide();
					}
					else {
						$('.nav').toggle();
						var tbody = $('#log > tbody');
						var tpl   = tbody.find('tr.log-line:first').clone();

						for (var i = 0, len = data.length; i < len; ++i) {
							var row = data[i];

							for (var key in row) {
								if (!row.hasOwnProperty(key)) continue;
								$('.group-' + key, tpl).text(row[key]);
							}

							tbody.append(tpl.clone());
						}

						if (tbody.find('tr').length > 100) {
							tbody.find('tr:lt(51)').remove();
						}
					}
				},
				complete: function() {
					$('#log > tbody').trigger('lines-added');
				}
			});

			return false;
		});
	});
	</script>
	<?php
}
