<?php
class gererFile {
	var $file = array();
	var $chaine = false;
	var $timestamp = 0;
	var $type = '';
	var $limite = 0;

	function gererFile($limite, $file, $type) {
		$this->limite = $limite;
		$this->type = $type;

		if (!empty($file)) {
			$file = explode(';', $file);
			$timestamp = $file[0];
			unset($file[0]);
			$file = array_merge($file);
			$cnt = count($file);
			for($i = 0; $i < $cnt; $i++){
				$file[$i] = explode(',', $file[$i]);
			}
			$this->file = $file;
		}
		else $this->timestamp = time();
	}

	function addObjet($objet,$nombre,$temps) {
		$this->file = array_merge($this->file);
		$nbF = count($this->file);
		if ($nbF >= $this->limite) return false;
		$this->chaine = false;
		if($nbF == 0) $this->timestamp = time();
		if($nbF > 0 && $this->file[$nbF-1][0] == $objet) $this->file[$nbF-1][1] += $nombre;
		else $this->file[] = array($objet, $nombre, $temps);
		return true;
	}

	function existe($objet) {
		$this->file = array_merge($this->file);
		$nbF=count($this->file);
		for ($i=0 ; $i<$nbF ; $i++){
			if($objet == $this->file[$i][0]) return true;
		}
		return false;
	}

	function delobjet($objet, $nombre=1) {
		$this->file = array_merge($this->file);
		for($i = count($this->file)-1; $i >= 0; $i--) {
			if($this->file[$i][0] == $objet){
				$nombre = min($nombre, $this->file[$i][1]);
				$this->file[$i][1] -= $nombre;
				if($this->file[$i][1] <= 0) {
					unset($this->file[$i]);
					$this->file = array_merge($this->file);
				}
				break;
			}
			if ($i == 1) $this->timestamp = time();
		}
		return $nombre;
	}

	function pret() {
		$this->file = array_merge($this->file);
		$out = array();
		$nbF = count($this->file);
		if ($nbF == 1 && $this->chaine) {
			$nb = floor((time()-$this->timestamp)/$this->file[0][2]);
			if ($nb > 0) {
				$out[] = array($this->file[0][0], $nb);
				$this->timestamp += $nb * $this->file[0][2];
			}
		}
		elseif ($nbF != 0) {
			$this->file = array_merge($this->file);
			for($i=0 ; $i<$nbF ; $i++){
				$tps = time() - $this->timestamp;
				if($this->file[$i][1] * $this->file[$i][2] < $tps) {
					$out[] = array($this->file[$i][0], $this->file[$i][1]);
					$this->timestamp += $this->file[$i][1] * $this->file[$i][2];
					unset($this->file[$i]);
				}
				elseif ($this->file[$i][2] < $tps) {
					for($j=0 ; $j*$this->file[$i][2]<$tps ; $j++) {}
					$j--;
					$out[] = array($this->file[$i][0], $j);
					$this->timestamp += $j * $this->file[$i][2];
					$this->file[$i][1] -= $j;
					break;
				}
				else {
					return $out;
				}
			}
			$this->file = array_merge($this->file);
		}
		return $out;
	}

	function export(){
		$nbF = count($this->file);
		$out = '';
		for($i=0;$i<$nbF;$i++){
			$out .= implode(',',$this->file[$i]).';';
		}
		return $out;
	}
}
?>