<?php
/**
 * Legt Logs für eine History von Userupdates an.
 * 
 * @license myHP, the construct for every webpage you want.
    Copyright (C) 2010  Stefan 'Eichi' Eichhorst <eichi@blubbbel.de>
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @package EoT-Clan BF3 Leaderboard
 * @copyright Eichi (Stefan Eichhorst)
 * @author Eichi - eichi@blubbbel.eu
 */

class history extends logging 
{
	
	protected $iPid = -1;
	const HISTORY_LINES = 8;
	
	/**
	 * Bestimmt welches Log bedient werden soll.
	 * 
	 * @param Integer $iPid
	 */
	public function __construct($iPid)
	{
		$this->iPid = $iPid;
		$this->setFile(LOG_DIR . $iPid . DS . 0 . self::SUFFIX);
	}
	
	/**
	 * Methode überschreibt setFile aus logging
	 * 
	 * @param String $sFile
	 */
	public function setFile($sFile)
	{
		if (intval(basename($sFile, self::SUFFIX))+1 >= self::MAX_LOGS) 
			exit('Error, the maximum of logs in ' . dirname($sFile) . ' exhausted, please report to the administrator.');
		$this->sFile = dirname($sFile) . DS . (intval(basename($sFile, self::SUFFIX))+1) . self::SUFFIX;
		if (file_exists($this->sFile) && count(file($this->sFile)) >= self::MAX_LINES) {
			$this->setFile($this->sFile);
		}
	}
	
	/**
	 * Zählt Zeilen der History eines Nutzers.
	 * Wenn statisch genutzt muss die Player-ID übergeben werden, 
	 * sonst wird die ID gewählt, mit der das Objekt instanziiert wurde.
	 *
	 */
	public static function countEntries($iPid)
	{
		if ($iPid < 0) $iPid = $this->iPid;
		if (!file_exists(LOG_DIR . $iPid)) return false;
		$aFiles = scandir(LOG_DIR . $iPid, 1);
		if ($aFiles === false) return false;
		rsort($aFiles);
		
		$aLines = array();
		for ($i = 0; $i < count($aFiles); ++$i) {
			if (is_file(LOG_DIR . $iPid . DS . $aFiles[$i]))
				$aLines = array_merge($aLines, file(LOG_DIR . $iPid . DS . $aFiles[$i]));
		}
		
		return count($aLines);
	}
	
	/**
	 * Gibt die letzte History zurück.
	 * Wenn statisch genutzt muss die Player-ID übergeben werden, 
	 * sonst wird die ID gewählt, mit der das Objekt instanziiert wurde.
	 * 
	 * @see Const HISTORY_LINES
	 * @param Integer $iPid = -1
	 * @param Integer $iPage = 1
	 * 
	 * @return Array
	 */
	public static function getHistoryLines($iPid = -1, $iPage = 1)
	{
		if ($iPid < 0) $iPid = $this->iPid;
		if (!file_exists(LOG_DIR . $iPid)) return false;
		$aFiles = scandir(LOG_DIR . $iPid, 1);
		if ($aFiles === false) return false;
		rsort($aFiles);
		$aLinesTmp = file(LOG_DIR . $iPid . DS . $aFiles[0]);
		if (intval(basename($aFiles[0], self::SUFFIX)) > 1 && (count($aLinesTmp) < self::HISTORY_LINES || $iPage > 1)) {
			if (count($aFiles) > 1) {
				if ($iPage == 1) {
					$aLinesTmp = array_merge($aLinesTmp, file(LOG_DIR . $iPid . DS . $aFiles[1]));
				} else {
					for ($i = 1; $i < count($aFiles); ++$i) {
						if (is_file(LOG_DIR . $iPid . DS . $aFiles[$i]))
							$aLinesTmp = array_merge($aLines, file(LOG_DIR . $iPid . DS . $aFiles[$i]));
					}
				}
			} else {
				exit('Error in ' . __FILE__ . ' at Line ' . __LINE__ . ': Bad history organization.');
			}
		}
		--$iPage;
		if ($iPage == 0) {
			$iFrom = 0;
		} else {
			$iFrom = $iPage * self::HISTORY_LINES;
		}
		$iTo = $iPage * self::HISTORY_LINES + self::HISTORY_LINES;
		for ($i = $iFrom; $i < $iTo; ++$i) $aLines[$i] = $aLinesTmp[$i];
		
		return $aLines;
	}
	
	/**
	 * Gibt die letzte History in einem Array aus.
	 * Wurden Werte mit => zugewiesen, wird dies verwendet um ein assoziatives Array aufzubauen.
	 *
	 * @param Integer $iPid = -1
	 * @param Integer $iPage = 1
	 
	 * @return Array
	 */
	public static function getHistory($iPid = -1, $iPage = 1)
	{
		$aHistoryLines = self::getHistoryLines($iPid, $iPage);
		if ($aHistoryLines === false) return false;
		$i = 0;
		foreach ($aHistoryLines as $sLine) {
			if (strlen($sLine) > 5) {
				$aLine = explode(';', $sLine);
				foreach ($aLine as $sValue) {
					$iHit = strpos($sValue, '=>');
					if ($iHit >= 1) {
						$aHistory[$i][substr($sValue, 0, $iHit)] = substr($sValue, $iHit+2);
					} else {
						$aHistory[$i][] = $sValue;
					}
				}
				++$i;
			}
		}
		
		return $aHistory;
	}
	
	/**
	 * Speichert die nächste History.
	 * Wird die Player-ID nicht übergeben, wird die ID verwendet mit der das Objekt instanziiert wurde.
	 * 
	 * @param Integer $iPid = -1
	 */
	public function saveHistory($mEntry, $iPid = -1)
	{
		if ($iPid < 0) $iPid = $this->iPid;
		$sEntry = '';
		if (is_array($mEntry)) {
			foreach ($mEntry as $kEntry => $vEntry) $sEntry .= ";{$kEntry}=>{$vEntry}"; 
		} else if (is_string($mEntry)) {
			$sEntry = ';' . $mEntry;
		}
		$this->setFile(LOG_DIR . $iPid . DS . 0 . self::SUFFIX);
		$this->appendLog(date('Y-m-d H:i:s') . $sEntry . "\r\n", '', false);
	}
	
	/**
	 * Gibt eine HTML-Tabelle für die Ausgabe in einem String zurück.
	 *
	 * @param Integer $iPid = -1
	 * @param Integer $iPage = 1
	 
	 * @return String
	 */
	public static function createTable($iPid = -1, $iPage = 1)
	{
		if ($iPid < 0) $iPid = $this->iPid;
		
		$sSql = "SELECT soldiername FROM " . DBPrefix . "generalStats WHERE pid = {$iPid}";
		$aSoldier = mysql_fetch_assoc(mysql_query($sSql));
		$sSoldier = $aSoldier['soldiername'];
		$sTable = "
			<tr>
			<td class='head' colspan='15'>
				<a style='margin-left:5px;float:left;margin-top:1px;font-size:10px;' href='stats.php?name=".htmlspecialchars($sSoldier)."'>
				 " . LANG_HISTORY_BACK . htmlspecialchars($sSoldier) . "
						</a>
						" . LANG_HISTORY_TITLE . $sSoldier . "</td>";
		


		$aHistory = self::getHistory($iPid, $iPage);
		$bListed = false;
		
		foreach($aHistory as $vHistory) {
			
			if (!$vHistory[0]){
				$hDate =  "--";
			} else {
				$aExpDate = explode(' ', $vHistory[0]);
				$aDetDate = explode('-', $aExpDate[0]);
				$hDate = "{$aDetDate[2]}.{$aDetDate[1]}.{$aDetDate[0]} {$aExpDate[1]}";
			}
			
			
			$points = number_format($vHistory['totalscore'], 0, ',', ' ');
			$team = number_format($vHistory['team'], 0, ',', ' ');
			$kills = number_format($vHistory['kills'], 0, ',', ' ');
			$rank = "<img src='img/rank/P0".$vHistory['rankimg'].".png' border='0' title='Rank ".$vHistory['rankimg']."'/>";
			
			global $domain;
			
			if ($vHistory['rank'] > 0){
				$rankup = "<img src='".$domain."/img/rank/up.png' border='0' />";
			}else{
				$rankup = "<img src='".$domain."/img/rank/gleich.png' border='0' />";
			}
			
			$deaths = number_format($vHistory['deaths'], 0, ',', ' ');
			$wins = number_format($vHistory['wins'], 0, ',', ' ');
			$looses = number_format($vHistory['looses'], 0, ',', ' ');
			$games = $vHistory['games'];
			$dogtag = $vHistory['dogtag'];
			$revives = $vHistory['revives'];
			$resupplies = $vHistory['resupplies'];
			$headshots = $vHistory['headshots'];
			$shots = number_format($vHistory['shots'], 0, ',', ' ');
			$hits = number_format($vHistory['hits'], 0, ',', ' ');
			if ($vHistory['shots'] > 0){
			$ac = number_format($vHistory['hits']*100/$vHistory['shots'], 2, ',', ' ');;
		}else{
			$ac = 0;
		}
			
			
			
			
			$heals = number_format($vHistory['heals'], 2, ',', '.');
			$time =  sprintf("%02dh %02dm",$vHistory['time']/60/60,$vHistory['time']/60%60);
			
			 if ($vHistory['deaths'] > 0 ){
         $KD = $vHistory['kills']/$vHistory['deaths'];
       }else{
      	 $KD = 0;
       }       
     $KD = number_format($KD, 2, ',', '.');       
       if ($KD >= 1){
         $result = '<font class="positiv">'.$KD.'</font>';
       }else{
   	     $result = '<font class="negativ">'.$KD.'</font>';
       }           
			

			if ($vHistory['time'] == 0) {
				$PpM = '----';
			} else {
				$PpM_min = ($vHistory['time']/60);
				$PpM_p = $vHistory['totalscore']/$PpM_min;
				$PpM = number_format($PpM_p, 2, ',', '.');
			}
			
			
			 if ($looses > 0 ){
         $WL = $wins/$looses;
       }else{
      	 $WL = 0;
       }       
			$WL = number_format($WL, 2, ',', '.');       
       if ($WL >= 1){
         $resultWL = '<font class="positiv">'.$WL.'</font>';
       }else{
   	     $resultWL = '<font class="negativ">'.$WL.'</font>';
       }           
			
			
			
			
			$weaponsName = 'LANG_WEAPONS_'.$vHistory['weapon'];
			$vehiclesName = 'LANG_VEHICLES_'.$vHistory['vehicles'];
			
			$Vtime =  sprintf("%02dm %02ds",$vHistory['vehiclesTime']/60,$vHistory['vehiclesTime']%60);
			
			
			
			   $rankname = array(
       "0" => "Private",
       "1" => "Private First Class I",
       "2" => "Private First Class II",
       "3" => "Private First Class III",
       "4" => "Private First Class IV",
       "5" => "Lance Corporal I",
       "6" => "Lance Corporal II",
       "7" => "Lance Corporal III",
       "8" => "Lance Corporal IV",
       "9" => "Corporal I",
       "10" => "Corporal II",
       "11" => "Corporal III",
       "12" => "Corporal IV",
       "13" => "Sergeant I",
       "14" => "Sergeant II",
       "15" => "Sergeant III",
       "16" => "Sergeant IV",
       "17" => "Staff Sergeant I",
       "18" => "Staff Sergeant II",
       "19" => "Staff Sergeant III",
       "20" => "Gunnery Sergeant I",
       "21" => "Gunnery Sergeant II",
       "22" => "Gunnery Sergeant III",
       "23" => "Master Sergeant I",
       "24" => "Master Sergeant II",
       "25" => "Master Sergeant III",
       "26" => "First Sergeant I",
       "27" => "First Sergeant II",
       "28" => "First Sergeant III",
       "29" => "Master Gunnery Sergeant I",
       "30" => "Master Gunnery Sergeant II",
       "31" => "Master Gunnery Sergeant III",
       "32" => "Sergeant Major I",
       "33" => "Sergeant Major II",
       "34" => "Sergeant Major III",
       "35" => "Warrant Officer",
       "36" => "Chief Warrant Officer 2",
       "37" => "Chief Warrant Officer 3",
       "38" => "Chief Warrant Officer 4",
       "39" => "Chief Warrant Officer 5",
       "40" => "Second Lieutenant",
       "41" => "First Lieutenant",
       "42" => "Captain",
       "43" => "Major",
       "44" => "Colonel",
       "45" => "Colonel II",
       "46" => "Colonel Service Star 1",
       "47" => "Colonel Service Star 2",
       "48" => "Colonel Service Star 3",
       "49" => "Colonel Service Star 4",
       "50" => "Colonel Service Star 5",
       "51" => "Colonel Service Star 6",
       "52" => "Colonel Service Star 7",
       "53" => "Colonel Service Star 8",
       "54" => "Colonel Service Star 9",
       "55" => "Colonel Service Star 10",
       "56" => "Colonel Service Star 11",
       "57" => "Colonel Service Star 12",
       "58" => "Colonel Service Star 13",
       "59" => "Colonel Service Star 14",
       "60" => "Colonel Service Star 15",
       "61" => "Colonel Service Star 16",
       "62" => "Colonel Service Star 17",
       "63" => "Colonel Service Star 18",
       "64" => "Colonel Service Star 19",
       "65" => "Colonel Service Star 20",
       "66" => "Colonel Service Star 21",
       "67" => "Colonel Service Star 22",
       "68" => "Colonel Service Star 23",
       "69" => "Colonel Service Star 24",
       "70" => "Colonel Service Star 25",
       "71" => "Colonel Service Star 26",
       "72" => "Colomel Service Star 27",
       "73" => "Colonel Service Star 28",
       "74" => "Colonel Service Star 29",
       "75" => "Colonel Service Star 30",
       "76" => "Colonel Service Star 31",
       "77" => "Colonel Service Star 32",
       "78" => "Colonel Service Star 33",
       "79" => "Colonel Service Star 34",
       "80" => "Colonel Service Star 35",
       "81" => "Colonel Service Star 36",
       "82" => "Colonel Service Star 37",
       "83" => "Colonel Service Star 38",
       "84" => "Colonel Service Star 39",
       "85" => "Colonel Service Star 40",
       "86" => "Colonel Service Star 41",
       "87" => "Colonel Service Star 42",
       "88" => "Colonel Service Star 43",
       "89" => "Colonel Service Star 44",
       "90" => "Colonel Service Star 45",
       "91" => "Colonel Service Star 46",
       "92" => "Colonel Service Star 47",
       "93" => "Colonel Service Star 48",
       "94" => "Colonel Service Star 49",
       "95" => "Colonel Service Star 50",
       "96" => "Colonel Service Star 51",
       "97" => "Colonel Service Star 52",
       "98" => "Colonel Service Star 53",
       "99" => "Colonel Service Star 54",
       "100" => "Colonel Service Star 55",
       "101" => "Colonel Service Star 56",
       "102" => "Colonel Service Star 57",
       "103" => "Colonel Service Star 58",
       "104" => "Colonel Service Star 59",
       "105" => "Colonel Service Star 60",
       "106" => "Colonel Service Star 61",
       "107" => "Colonel Service Star 62",
       "108" => "Colonel Service Star 63",
       "109" => "Colonel Service Star 64",
       "110" => "Colonel Service Star 65",
       "111" => "Colonel Service Star 66",
       "112" => "Colonel Service Star 67",
       "113" => "Colonel Service Star 68",
       "114" => "Colonel Service Star 69",
       "115" => "Colonel Service Star 70",
       "116" => "Colonel Service Star 71",
       "117" => "Colonel Service Star 72",
       "118" => "Colonel Service Star 73",
       "119" => "Colonel Service Star 74",
       "120" => "Colonel Service Star 75",
       "121" => "Colonel Service Star 76",
       "122" => "Colonel Service Star 77",
       "123" => "Colonel Service Star 78",
       "124" => "Colonel Service Star 79",
       "125" => "Colonel Service Star 80",
       "126" => "Colonel Service Star 81",
       "127" => "Colonel Service Star 82",
       "128" => "Colonel Service Star 83",
       "129" => "Colonel Service Star 84",
       "130" => "Colonel Service Star 85",
       "131" => "Colonel Service Star 86",
       "132" => "Colonel Service Star 87",
       "133" => "Colonel Service Star 88",
       "134" => "Colonel Service Star 89",
       "135" => "Colonel Service Star 90",
       "136" => "Colonel Service Star 91",
       "137" => "Colonel Service Star 92",
       "138" => "Colonel Service Star 93",
       "139" => "Colonel Service Star 94",
       "140" => "Colonel Service Star 95",
       "141" => "Colonel Service Star 96",
       "142" => "Colonel Service Star 97",
       "143" => "Colonel Service Star 98",
       "144" => "Colonel Service Star 99",
       "145" => "Colonel Service Star 100");
			
			if(strlen(constant($weaponsName)) <= 8) {
        $weaponN = constant($weaponsName);
      } else {
        $weaponN = substr(constant($weaponsName),0,8) . ''; 
      }      
			
			if(strlen(constant($vehiclesName)) <= 8) {
        $vehiclesN = constant($vehiclesName);
      } else {
        $vehiclesN = substr(constant($vehiclesName),0,8) . ''; 
      }      
			
			if ($vHistory['vehiclesTime'] <= 0 ){
				$vehiclesR = '---';
			}else{
				$vehiclesR = '<a class="tooltip">'.$vehiclesN.'('.$Vtime.')<span style="margin-left:-160px;margin-top:-40px;width:140px;">'.constant($vehiclesName).'<br><img src="'.$domain.'/img/vehicles/'.$vHistory['vehicles'].'.png" width="130px;" /></span></a>';
			}
			
			
			$skill = substr($vHistory['skill'],0,1);
			if ($skill == "+"){
				$skill = '+'.number_format($vHistory['skill'], 2, ',', '.');
			}else{
				$skill = number_format($vHistory['skill'], 2, ',', '.');
			}
			
		
			$sTable .= '<tr><td>
				<div class="bgDIV" style="width:805px;height:120px;margin-left:3px;margin-top:5px;-moz-box-shadow: 2px 2px 4px #5C5B5B;-webkit-box-shadow: 2px 2px 4px #5C5B5B;box-shadow: 2px 2px 4px #5C5B5B;">
				   <div style="text-align:left;font-weight:bold;border-bottom:1px solid #333333"">'.LANG_HISTORY_HEAD_DATE.$hDate.'</div><br />
				   <div style="float:left;width:120px;font-size:11px;">
				       <span style="float:left;">'.LANG_HISTORY_HEAD_TIME.'</span><span style="float:right;">'.$time.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_POINTS.'</span><span style="float:right;">'.$points.'</span><br />
				       <span style="float:left;">Team</span><span style="float:right;">'.$team.'</span><br />
				       <span style="float:left;">Dogtags</span><span style="float:right;">'.$dogtag.'</span><br /> 
				       <span style="float:left;">'.LANG_HISTORY_HEAD_ROUNDS.'</span><span style="float:right;">'.$games.'</span><br />
				       <span style="float:left;">Ppm</span><span style="float:right;">'.$PpM.'</span><br />
				     </div>
				     
				     <div style="float:left;width:120px;margin-left:20px;font-size:11px;">
				       <span style="float:left;">Kills</span><span style="float:right;">'.$kills.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_DEATHS.'</span><span style="float:right;">'.$deaths.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_HEADSHOTS.'</span><span style="float:right;">'.$headshots.'</span><br />
				       <span style="float:left;">Skill</span><span style="float:right;">'.$skill.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_KD.'</span><span style="float:right;">'.$result.'</span><br />
				     </div>
				     
				     <div style="float:left;width:120px;margin-left:20px;font-size:11px;">
				       <span style="float:left;">'.LANG_HISTORY_HEAD_SHOTS.'</span><span style="float:right;">'.$shots.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_HITS.'</span><span style="float:right;">'.$hits.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_AC.'</span><span style="float:right;">'.$ac.'%</span><br /> 
				        <span style="float:left;">Medals</span><span style="float:right;">'.$vHistory['medals'].'</span><br />
				        <span style="float:left;">Ribbons</span><span style="float:right;">'.$vHistory['ribbons'].'</span><br />
				        <span style="float:left;">'.LANG_HISTORY_HEAD_CLASS.'</span><span style="float:right;"><img src="'.$domain.'/img/fav/'.$vHistory['class'].'.png" title="'.$vHistory['class'].'" /></span><br />
				     </div>
				        
				      <div style="float:left;width:120px;margin-left:20px;font-size:11px;">
				       <span style="float:left;">'.LANG_HISTORY_HEAD_WINS.'</span><span style="float:right;">'.$wins.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_LOOS.'</span><span style="float:right;">'.$looses.'</span><br />
				       <span style="float:left;">W/L</span><span style="float:right;">'.$resultWL.'</span><br />  
				       <span style="float:left;">'.LANG_HISTORY_HEAD_HEALS.'</span><span style="float:right;">'.$heals.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_REVIVES.'</span><span style="float:right;">'.$revives.'</span><br />
				       <span style="float:left;">'.LANG_HISTORY_HEAD_RESUPPLIES.'</span><span style="float:right;">'.$resupplies.'</span><br />
				     </div>
				        
				     <div style="float:left;width:100px;height:90px;margin-left:20px;font-size:11px;">
				      <span style="float:left;"><img src="'.$domain.'/img/rank/big/P0'.$vHistory['rankimg'].'.png" width="70px"/></span>
	  			     <span style="float:right;margin-top:15px;">'.$rankup.'</span><br />
	  			     <span style="float:left;position:absolute;margin-top:50px;margin-left:-10px;"><b>'.$rankname[$vHistory['rankimg']].' ('.$vHistory['rankimg'].')</b></span>   
				     </div>
				     
				     <div style="float:left;width:125px;margin-left:20px;font-size:11px;">
				       <span style="float:right;"><a class="tooltip">'.$weaponN.' ('.$vHistory['wkills'].' kills)<span style="margin-left:-160px;margin-top:-40px;width:140px;">'.constant($weaponsName).'<br><img src="'.$domain.'/img/weapons/'.$vHistory['weapon'].'.png" width="130px;" /></span></a></span><br />
				       <span style="float:right;">'.$vehiclesR.'</span><br />		       
				            <span style="float:right;">
				              <div>
	  			       		   <img src="'.$domain.'/img/stars/stars_back.png" style="float:left;"/>
	  			              <div style="margin-left:29px;position:absolute;font-size:11px"><b>'.$vHistory['stars'].'</b></div>
	  			           </div>
	  			         </span>
				     </div>
				</div>
			</td>';
			$bListed = true;
		}
		
		if ($bListed === false){
			$sTable .= "
				<tr>
					<td colspan='20' style='font-size: 12px;' class='result'>" . LANG_HISTORY_ERROR . "</td>
				</tr>
			";
		}
		return $sTable;
	}
	
}
