<?php
/*
 * jde, 08/08/17, updated to run as a class
 *
 * jde, Original coding,  August 09 as part of helpsys, taken from Chapman&Chapman book
 **/

require_once 'db.inc.php';

class Cloud {

    function __construct( $cloudSize ) {
      if ( ( $cloudSize > 0 ) && ( $cloudSize < $this->MAXCLOUDSIZE ) )
         $this->_cloudSize = $cloudSize;
	  //echo 'Cloud size set to ' . $this->_cloudSize . '<br/>';
    }

	public function doCloud() {
		$query = "select * from counts order by count desc limit " . $this->_cloudSize;
		$records = dbQuery( $query );
		$n = mysql_num_rows($records);
		if ($n > $this->MAXCLOUDSIZE) $n = $this->MAXCLOUDSIZE;
		for ($i = 0; $i < $n; ++$i) {
			$record = mysql_fetch_array($records);
			$counts[$record["term"]] = $record["count"];
		}
		return $this->makeCloud($counts);
	}

	private $MAXCLOUDSIZE = 50;
	private $_cloudSize = 12;

	private function normalize($v, $n1, $n2, $m) {
		return round((($v - $n1 + 1) * $m)/($n2 - $n1 + 1));
	}

	private function makeLink($t, $n) {
		$searchURL = "./src/php/glossarySearch.php?term1=$t&checkboxValue=N";
		return "<a class=\"al$n\" onClick=\"ContentLoader.loadSnippet( '$searchURL', 'SideNavigationLong', false );\" title=\"Look up $t\">$t</a>";
	}

	private function encloud($a) {
		$s = "";
		foreach ($a as $k => $v)
			$s .= $this->makeLink($k, $v) . " ";
		return $s;
	}

	private function makeCloud($counts) {
		$max = reset($counts);
		$min = end($counts);
		foreach ($counts as $k => $v)
			$counts[$k] = $this->normalize($v, $min, $max, 5);
		ksort($counts);
		return $this->encloud($counts);
	}

}
