<?php

class JSONUtil {


	static public function getNextID($dataArray, $id_property_name="id"){
	
		$nextId = 0;
		if(!is_array($dataArray) || count($dataArray)==0){

		}else{
			for($i=0; $i<count($dataArray); $i++){
				$nextId = max($nextId,$dataArray[$i]->$id_property_name);
			}
		}
		return $nextId+1;
		
	}
        
	static public function insertNewRow($jsonFile, $newRowObject, $id_property_name="id"){
	
		$jsonData = Util::readFile($jsonFile); 								// read
		$dataArray = DataSerializer::deserialize($jsonData); 				// desearilize
		$newId = self::getNextID($dataArray, $id_property_name); 		// get new id
		$newRowObject->$id_property_name = $newId; 							// add id to obj
		$dataArray[] = $newRowObject; 										// add row
		$jsonData = DataSerializer::serialize($dataArray); 					// serialize
		Util::writeFile($jsonFile, $jsonData); 								// write
		return $newId;
		
	}

	static public function updateRow($jsonFile, $newRowObject, $id, $id_property_name="id" ){
	
		$jsonData = Util::readFile($jsonFile); 								// read
		$dataArray = DataSerializer::deserialize($jsonData); 				// desearilize
	
		// how many rows are affected
		$count_updates = 0;
	
		if(!is_array($dataArray) || count($dataArray)==0){
			return 0;
		}else{
			for($i=0; $i<count($dataArray); $i++){
				if($dataArray[$i]->$id_property_name == $id){
				 	$newRowObject->$id_property_name = $id;
					$dataArray[$i] = $newRowObject;
					$count_updates ++;
				}
			}
		}
		$jsonData = DataSerializer::serialize($dataArray); 					// serialize
		Util::writeFile($jsonFile, $jsonData); 								// write
		
		return $count_updates;
		
	}

	static public function deleteRow($jsonFile,  $id, $id_property_name="id" ){
	
		$jsonData = Util::readFile($jsonFile); 								// read
		$dataArray = DataSerializer::deserialize($jsonData); 				// desearilize
	
		// how many rows are affected
		$count_updates = 0;
	
		if(!is_array($dataArray) || count($dataArray)==0){
			return 0;
		}else{
			for($i=0; $i<count($dataArray); $i++){
				if($dataArray[$i]->$id_property_name == $id){
				 	unset($dataArray[$i]);
					$dataArray = array_values($dataArray);
					$count_updates ++;
				}
			}
		}
		$jsonData = DataSerializer::serialize($dataArray); 					// serialize
		Util::writeFile($jsonFile, $jsonData); 								// write
		
		return $count_updates;
		
	}
	
	
	static public function updateObject($jsonFile, $sourceObject){
	
		$jsonData = Util::readFile($jsonFile); 								// read
		$dataObject = DataSerializer::deserialize($jsonData); 				// desearilize
	
		// update
		foreach($sourceObject as $key => $value) {
           $dataObject->$key = $value;
		}
       
		$jsonData = DataSerializer::serialize($dataObject); 				// serialize
		Util::writeFile($jsonFile, $jsonData); 								// write
		
	}
	
}