<?php

class ArchiveState {
	
	public $query = '';
	public $regex = false;
	
	public $page   = null;
	public $pagect = null;
	public $year   = null;
	public $month  = null;
	
	protected $hubid = null;
	protected $hub   = null;
	
	public function __construct() {}
	
	public function setHub($hubid) {
		$hubs = getHubs();
		if (array_key_exists($hubid, $hubs)) {
			$this->hubid = $hubid;
			$this->hub = $hubs[$hubid];
		}
	}
	
	public function renderView() {
		if (is_null($this->hubid)) $this->renderError('Invalid hub selected');

		$this->year   = clamp($this->year, $this->hub[2], $this->hub[4]);
		$this->month  = clamp($this->month, 1, 12);

		$chat = @file_get_contents(strftime($this->hub[1], strtotime($this->year.'-'.$this->month)));
		if ($chat === false) {
			$OUTPUT = 'No logs for the selected month.';

		} else {
			// Pick page

			$chat = explode("\n", rtrim($chat, "\n"));
			
			$this->pagect = ceil(count($chat) / D_LINES_PER_PAGE) - 1;
			if (is_null($this->page)) {
				$this->page = $this->pagect;
			} else {
				$this->page = clamp($this->page, 0, $this->pagect);
			}

			$line = D_LINES_PER_PAGE*$this->page;
			$end_line = min(count($chat), D_LINES_PER_PAGE*($this->page+1)); // - 1;

			$OUTPUT = '';

			for($line = D_LINES_PER_PAGE*$this->page; $line < $end_line; $line++) {
				$OUTPUT .= hesc($chat[$line])."<br>\n";
			}

		}

		return $this->renderTemplate($OUTPUT);
	}

	public function renderSearch() {
		if (is_null($this->hubid)) $this->renderError('Invalid hub selected');

		$RXSEARCH = null;

		if ($this->regex) {
		
			// Escape regex delimeter
			$RXSEARCH = '/'.preg_replace_callback('~[\\\\]*/~', function($m) {
				$ct = strlen($m[0])-1;
				$odd = !! ($ct%2);
				$rep = $odd ? $ct + 1 : $ct;
				return str_repeat('\\', $rep).'\\/';
			}, $this->query).'/i';
			
			// $RXSEARCH = '/'.str_replace('/', '\\/', $this->query).'/i';
			
			if (@preg_match($RXSEARCH, '') === false) {
				$err = error_get_last();
				$this->renderError('Invalid regular expression "<tt>'.hesc($RXSEARCH).'</tt>".<br>'.hesc($err['message']));
			}
		}

		$results = array();
		
		foreach(monthrange($this->hub[2], $this->hub[3], $this->hub[4], $this->hub[5]) as $ympair) {
			list($y, $m) = $ympair;
			
			$chatfile = @file_get_contents(strftime($this->hub[1], strtotime($y.'-'.$m)));
			if ($chatfile === false) continue;
			$chat = explode("\n", $chatfile);

			for ($i = 0, $e = count($chat); $i < $e; $i++) {
				if (
					(!$this->regex && (stripos($chat[$i], $this->query) !== false))
					||
					($this->regex && (preg_match($RXSEARCH, $chat[$i]) === 1))
				) {
					$page = floor($i / D_LINES_PER_PAGE);
					$lineno = $i % D_LINES_PER_PAGE;
					$url = '?h='.$this->hubid.'&y='.$y.'&m='.$m.'&p='.$page.'#line-'.$lineno;
					
					$results[] = '<a href="'.hesc($url).'">&raquo;</a> '.hesc($chat[$i]);
				}
			}
		}
		
		$OUTPUT = (count($results)) ?
			'<em>Found '.count($results).' result(s).</em><br><br><ul><li>'.implode('</li><li>', $results).'</li></ul>' :
			'No search results for "<em>'.hesc($this->query).'</em>"'
		;

		return $this->renderTemplate($OUTPUT);
	}

	/**
	 * 
	 * @param type $sz
	 * @return type
	 */
	public function renderError($sz) {
		return $this->renderTemplate($sz);
	}

	/**
	 * 
	 * @param type $body
	 */
	protected function renderTemplate($body) {
		
		header('Content-Type: text/html; charset=UTF-8');
		header('X-UA-Compatible: IE=Edge');

		if (is_null($this->hubid)) {
			$title = 'Archives';
		} else {
			$title = $this->hub[0].' Archives';
		}
		
		$show_page_urls = (
			!is_null($this->hubid) && !strlen($this->query)
		);
		if ($show_page_urls) {
			$pagebase = '/'.$this->hubid.'/'.$this->year.'/'.$this->month;
		}

?>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<title><?=hesc($title)?></title>
		<link rel="stylesheet" type="text/css" href="/style.css">
	</head>
	<body>
		<div class="layout-top nav">
		
			<div id="tr1" style="display:none;"></div>
			<div id="tr2" style="display:none;"></div>
			<div class="ddmenu" id="spm" style="display:none;">
				<a href="/">Latest</a>
				<a onclick="fontSize(1);">Font increase</a>
				<a onclick="fontSize(-1);">Font decrease</a>
				<a href="/download" onclick="return confirm('Are you sure you want to download a backup?');">Download backup</a>
			</div>
		
			<a onclick="toggleMenu();"><div id="logo" class="layout-pushdown"></div></a>
		
			<span class="area-nav">
			
			<form method="GET" id="frmHub">
				<select name="h" id="selHub">
	<? foreach (getHubs() as $hkey => $h) { ?>
					<option value="<?=$hkey?>" <?=($hkey==$this->hubid)?'selected':''?>><?=hesc($h[0])?></option>
	<? } ?>
				</select>
			</form>

<? if ($show_page_urls) { ?> 
			
			<form method="GET">
				<input type="hidden" name="h" value="<?=$this->hubid?>"> 
				<select id="seldate" onchange="setYM(this);">
<?php

// Generate month dropdown options

$lasty = null;
foreach(monthrange($this->hub[2], $this->hub[3], $this->hub[4], $this->hub[5]) as $ympair) {
	list($y, $m) = $ympair;
	if ($y !== $lasty) {
		if ($lasty !== null) {
			echo '</optgroup>';
		}
		echo '<optgroup label="'.$y.'">'."\n";
		$lasty = $y;
	}
	echo '<option value="'.$y.'-'.$m.'" '.(($y==$this->year & $m==$this->month)?'selected':'').'>'.month($m)."</option>\n";
}
echo '</optgroup>';
?> 
				</select>
				<input type="hidden" name="y" id="f_y" value="">
				<input type="hidden" name="m" id="f_m" value="">
				<input type="hidden" name="p" value="0" >
			</form>
			
			<div class="mini-separator layout-pushdown"></div>
			
			<a class="btn" href="<?=$pagebase?>/0">&laquo;</a><a
			   class="btn" id="pgprev" href="<?=$pagebase?>/<?=max(0,$this->page-1)?>">&lsaquo;</a>
			<?=$this->page?>
			<a class="btn" id="pgnext" href="<?=$pagebase?>/<?=min($this->pagect,$this->page+1)?>">&rsaquo;</a><a
			   class="btn" href="<?=$pagebase?>">&raquo;</a>
			
<? } ?> 
			<div class="pad"></div>

			</span>
			
			<span class="area-search">
			
			<form method="GET">
				<input type="hidden" name="h" value="<?=hesc($this->hubid)?>">
				<input type="text" id="searchbox" name="q" value="<?=hesc($this->query)?>" placeholder="Search...">
				<input type="submit" value="&raquo;">
				<input type="checkbox" class="layout-pushdown" name="rx" value="1" title="PCRE Regular Expression" <?=($this->regex ? 'checked' : '')?>>
			</form>
			
			</span>
		</div>
		
		<div class="layout-body" id="chatarea">
<?=$body?> 
		</div>
		<script type="text/javascript" src="/archive.js?nonce=<?=filemtime(__DIR__.'/../wwwroot/archive.js')?>"></script>
	</body>
</html>
<?php

		die();

	}

}