<?php

class Util {


    public static function getMesAnioAnterior($mes,$anio){

        $mes = round($mes);
        $anio = round($anio);

        if($mes >= 1 && $mes<=12) {
            if ($mes > 1) {
                $nuevoMes = $mes - 1;
                $nuevoAnio = $anio;
            } else {
                $nuevoMes = 12;
                $nuevoAnio = $anio -1;
            }
        }
        return array('mes'=>$nuevoMes,'anio'=>$nuevoAnio);

    }
    public static function getDiaSemana($numDia) {
        $ds[1] = "Lunes";
        $ds[2] = "Martes";
        $ds[3] = "Miércoles";
        $ds[4] = "Jueves";
        $ds[5] = "Viernes";
        $ds[6] = "Sábado";
        $ds[7] = "Domingo";
        return ($numDia>=1 && $numDia <=7)?$ds[$numDia]:"-";
    }
    public static function getMesAnioSiguiente($mes,$anio){

        $mes = round($mes);
        $anio = round($anio);

        if($mes >= 1 && $mes<=12) {
            if ($mes < 12) {
                $nuevoMes = $mes + 1;
                $nuevoAnio = $anio;
            } else {
                $nuevoMes = 1;
                $nuevoAnio = $anio + 1;
            }
        }
        return array("mes"=>$nuevoMes,"anio"=>$nuevoAnio);

    }

	public static function getRandomQueclinkRef(){
		return strtoupper(Util::fillWithZeroes(dechex(rand(0,65535)),4));
	}
	
	
	public static function xmlEncode($xml){

		$doc = new DOMDocument();
		$fragment = $doc->createDocumentFragment();
		
		// adding XML verbatim:
		$xml = "Test &amp; <b> and encode </b> :)\n";
		$fragment->appendXML($xml);
		
		// adding text:
		$text = $xml;
		$fragment->appendChild($doc->createTextNode($text));
		
		// output the result
		echo $doc->saveXML($fragment);
		
	}

	
	static function getFormatedDate($timestamp,$offset=SYS_TIMEZONE){
		return date("d/m H:i",$timestamp);
	}
	
	
	
	public static function toLittleEndian($anHexString) {
		$littleEndian = "";
		for($i = 0; $i < strlen ( $anHexString ); $i = $i + 2) {
			$byte = substr ( $anHexString, $i, 2 );
			$littleEndian = $byte . $littleEndian;
		}
		return $littleEndian;
	}
	
	
	public static function toDefinitionString($anArray){
		
		$aString = "";
		for($i=0;$i<count($anArray);$i++){
			$aString .= strtoupper(str_pad(dechex($anArray[$i]), 2,"0",STR_PAD_LEFT));
		}
		return $aString;
	}
	
	public static function toBytes($aText,$nullEnd = true){
		
		$bytes = "";
		for($i=0;$i<strLen($aText);$i++){
			$bytes[$i] = ord(substr($aText,$i,1));
			//$bytes .= strtoupper(str_pad(dechex($byte), 2,"0",STR_PAD_LEFT));
		}
		$bytes[$i+1] = 0;
		return $bytes;
	}
	
	public static function toByteString($aText){
		
		$bytes = "";
		for($i=0;$i<strLen($aText);$i++){
			$byte = ord(substr($aText,$i,1));
			$bytes .= strtoupper(str_pad(dechex($byte), 2,"0",STR_PAD_LEFT));
		}
		return $bytes;
	}
	
	
	public static function dlePadding($aMessage){
		
		$paddedMessage = "";
		for($i=0;$i<strLen($aMessage);$i++){
			$aChar = substr($aMessage,$i,1);
			$aChar .= ($aChar == chr(10))?$aChar:"";
			$paddedMessage .= $aChar;
		}
		return $paddedMessage;
	}
	
	public static function getChecksum($aString) {
		
		$sum = 0;
		for($i = 0; $i < strlen ( $aString ); $i = $i + 2) {
			$byte = substr ( $aString, $i, 2 );
			$byteValue = hexdec ( $byte );
			$sum += $byteValue;
		}
		
		$sum = 0xff & $sum;
		// perform 2s complement
		$sum = 0xff - $sum + 1;
		
		//echo ("computed checksum is " . $sum);
		return $sum;
	}

	public static function getChecksumOfArray($anArray) {
		
		$sum = 0;
		for($i = 0; $i < count($anArray); $i++) {
			$sum += $anArray[$i];
		}
		
		$sum = 0xff & $sum;
		// perform 2s complement
		$sum = 0xff - $sum + 1;
		
		//echo ("computed checksum is " . $sum);
		return $sum;
	}
	
	
	public static function longToBytes($aLong,$bytes){
		
		$byteArray = Array();
     	$num = $aLong;
		
		for($i=$bytes-1; $i>0; $i--){
			$divisor = pow(256,$i);
			$byte = floor($num/$divisor);
			$byteArray[$bytes-$i-1] = $byte;
			$num = $num - ($byte*$divisor);
		}
		$byteArray[$bytes-1] = $num;
		
        return $byteArray;
	}
	
	
	public static function toLittleEndianBytes($anArray){
		//echo "<pre>";
		//print_r($anArray);
		for($i=count($anArray)-1;$i>=0;$i--){
			$result[(count($anArray)-1)-$i] = $anArray[$i];
		}
		//print_r($result);
		return $result;
	}
	
	public static function arrayInsert($baseArray,$secondArray,$index=false){
		
		if($index===false) $index=count($baseArray);
		
		$result = null;
		for($i=0;$i<count($baseArray)+count($secondArray);$i++){
			if($i<$index) {
				$result[$i] = $baseArray[$i];
			} elseif($i > ($index+count($secondArray)-1)){
				$result[$i] = $baseArray[$i-$index];
			} else{
				$result[$i] = $secondArray[$i-$index];
			}
		}
		return $result;
	}
	
	public static function arrayAppend($a1,$a2){
		
		$a3=$a1;
		if(is_array($a2)){
			foreach($a2 as $i=>$content){
				$a3[] = $content;
			}
		}
		return $a3;
	}
	
	public static function dleStuff($anArray){
		$stuffed = Array();
		foreach($anArray as $aChar){
			if(ord($aChar) == DLE) $stuffed[] = DLE;
			$stuffed[] = $aChar;
		}
		return $stuffed;
	}
	
	public static function split($array,$index){
		
		
	}
	
	public function getRawFromDefinition($definitionString){
		$string = "";
		for($i=0; $i<strlen($definitionString);$i=$i+2){
			$byte = hexdec(substr($definitionString,$i,2));
			$string .= chr($byte);
			
		}
		return $string;
	}
	
	public static function splitTime($aTimeString){
		$aTimeString = trim($aTimeString);
		$splitDateTime = split(" ",$aTimeString);
		$dateFields = $splitDateTime[0];
		$timeFields = $splitDateTime[1];
		$splitDate = split("/",$dateFields);
		$splitTime = split(":",$timeFields);
		$r[0]=$splitDate[2];
		$r[1]=$splitDate[1];
		$r[2]=$splitDate[0];
		$r[3]=$splitTime[0];
		$r[4]=$splitTime[1];
		$r[5]=(isset($splitTime[2]))?$splitTime[2]:0;
		return $r;
	}
	
	public static function getLatLng($degrees) {
	
		if($degrees < 0){
			$degrees = $degrees+360;
		}
		//echo "Corr Deg: ".$degrees."<br>";
		$semicircles = floor($degrees * CONVERSION_K);
		//echo "SC: ".$semicircles."<br>";
		$scarray = Util::longToBytes($semicircles, 4);
		//echo "<pre>";
		//print_r($scarray);
		return Util::toLittleEndianBytes($scarray);
	}
	
	public static function getAbbreviatedTime($tsDif){
		
		if($tsDif==0){
			$abbr= "un instante";
		} elseif($tsDif < 60){
			$abbr = sprintf("%s seg%s",$tsDif,($tsDif>1)?"s":"");
		} elseif($tsDif < 3600){
			$minutos = floor($tsDif/60);
			$abbr = sprintf("%s min%s",$minutos,($minutos>1)?"s":"");
		} elseif($tsDif < (24 * 3600)){
			$horas = floor($tsDif/3600);
			$minutos = floor(($tsDif-($horas*3600))/60);
			$abbr = sprintf("%s hora%s",$horas,($horas != 1)?"s":"");
			$abbr .= ($minutos>0)?sprintf(" y %s minuto%s",$minutos,($minutos>1)?"s":""):"";
		} else {
			$dias = floor($tsDif/(24 * 3600));
			$horas = floor(($tsDif-($dias*24*3600))/3600);
			$abbr = sprintf("%s dia%s",$dias,($dias != 1)?"s":"");
			$abbr .= ($horas>0)?sprintf(" y %s hora%s",$horas,($horas>1)?"s":""):"";
		}
		return $abbr;
		
	}
	
	// Completa con "0" a la izquierda hasta que largo(prefijo + val) alcance len 
	public static function fillWithZeroes($val,$len){
		
		while(strlen($val) < $len){
			$val = "0".$val;
		}
		return $val;
		
	}
	
	
	public static function getFormattedTimeDiff($seconds,$noSeconds=false){
		
		//$days = floor($seconds / (24*3600));
		$hours = floor($seconds / 3600);
		$mins = floor(($seconds - ($hours*3600)) / 60);
		$secs = $seconds - ( $hours*3600 + $mins*60);
		
		$hours = Util::fillWithZeroes($hours,2);
		$mins = Util::fillWithZeroes($mins,2);
		$secs = Util::fillWithZeroes($secs,2);
		
		return ($noSeconds)?sprintf("%sh %s'",$hours,$mins):sprintf("%s:%s:%s",$hours,$mins,$secs);
		
	}
	

	
	function getTimeDiff($from,$to){
		return $to-$from;
	}
	
}

?>