<?php /** @noinspection PhpUnused */

class IceBoxStats extends Device {

	/**
	 * @throws BadRequestException
	 * @throws ServerException
	 */
	public static function getStats(): array {
		$countryCode=config::get("core_country_code");
		if(empty($countryCode)){ $countryCode=""; }
		$ret=["countryCode"=>$countryCode];
		$tables=['project','user','plate','dropimage','crystal'];
		$criteria=['issystem=0','isactive=1','','',''];
		if(count($criteria)!=count($tables)){
			throw new ServerException('table and criteria counts do not match');
		}
		for($i=0;$i<count($tables);$i++){
			$table=$tables[$i];
			$statement="SELECT SQL_CALC_FOUND_ROWS id FROM $table";
			if(!empty($criteria[$i])){
				$statement.=' WHERE '.$criteria[$i];
			}
			$statement.=' LIMIT 1';
			database::query($statement);
			$ret[$table]=database::getFoundRows();
		}
		$ret['phpVersion']=phpversion();
		$ret['codeVersion']='';
		$ret['databaseVersion']=config::getDatabaseVersion();
		$codeVersion=config::getCodeVersion();
		if(!empty($codeVersion)){
			$ret['codeVersion']=$codeVersion;
		}
		$disks=[];
		if(exec('df -h',$disks)){
			$labels=$disks[0];
			$labels=explode('|',preg_replace('/\s+/','|',$labels));
			$percentIndex=array_search('Use%', $labels);
			$totalIndex=array_search('Size', $labels);
			$usedIndex=array_search('Used', $labels);
			$freeIndex=array_search('Avail', $labels);
			$nameIndex=array_search('Mounted', $labels);
			if(false!==$percentIndex && false!==$totalIndex && false!==$usedIndex && false!==$freeIndex && false!==$nameIndex){
				$drives=[];
				for($i=1;$i<count($disks);$i++){
					$parts=$disks[$i];
					$parts=explode('|',preg_replace('/\s+/','|',$parts));
					if('/'===$parts[$nameIndex] || str_contains($parts[$nameIndex],'/icebearstore')){
						$drives[]=['name'=>$parts[$nameIndex], 'size'=>$parts[$totalIndex], 'used'=>$parts[$usedIndex], 'free'=>$parts[$freeIndex], 'usedPercent'=>(int)$parts[$percentIndex] ];
					}
				}
				$ret['disks']=$drives;
			}
		}
		return $ret;
	}

	/**
	 * @throws ServerException
	 * @throws BadRequestException
	 */
	public static function get(): array {
		return static::getStats();
	}

}