<?php
// Funcines para reconocer los ficheros contenidos en un campo de almacenamiento de ficheros
// Functions to recognize the files contained in a field

function countFiles($field){
	$fileArray = my_json_decode($field);
	return count($fileArray);
}

function countImagesVideos($field) {
	$fileArray = my_json_decode($field);
	$countImage = 0;
	$countVideo = 0;
	foreach ($fileArray as &$file) {	
		$type = $file['type'];
		$parts = explode("/", $type);
		switch ($parts[0]) {
    case "video":
        $countVideo += 1;
        break;
    case "image":
        $countImage += 1;
        break;
		}
	}
	return array($countImage, $countVideo);
	}

function arrayImages($field) {
	$return = [];
	$fileArray = my_json_decode($field);
	foreach ($fileArray as &$file) {	
		$type = $file['type'];
		$parts = explode("/", $type);
		if ( $parts[0] == 'image' ) {
				$return[] = $file['usrName'];
		}
	}
	return $return;
}

function onlyImages($field) {
	$numDelete = 0;
	$fileArray = my_json_decode($field);
	$return = $fileArray;
	for ($i = 0; $i < count($fileArray); $i++) {
		$type = $fileArray[$i]['type'];
		$parts = explode("/", $type);
		if ( $parts[0] <> 'image' ) {
				 unset($return[$i]);
				 $numDelete += 1;
		}
	}
	$return = my_json_encode($return);
	return $return;
}

function arrayVideos($field) {
	$return = [];
	$fileArray = my_json_decode($field);
	foreach ($fileArray as &$file) {	
		$type = $file['type'];
		$parts = explode("/", $type);
		if ( $parts[0] == 'video' ) {
				$return[] = $file['usrName'];
		}
	}
	return $return;
}

function searchImageOfVideo($field,$nameVideo) {
	$fileArray = my_json_decode($field);
	$parts = explode(".", $nameVideo);
	$name = $parts[0]; // name without extension

	foreach ($fileArray as &$file) {	
		$type = $file['type'];
		$parts = explode("/", $type);
		if($parts[0] == 'image') {
			$parts2 = explode(".", $file['usrName']);
			if ( $parts2[0] == $name ) { // Found File image equal name to the video file
					return array(true, $file['usrName']);
			}
		}
	}
	return array(false, NULL);
}

function searchMimeType($field,$nameFile) {
	$fileArray = my_json_decode($field);

	foreach ($fileArray as &$file) {	

		if($file['usrName'] == $nameFile) {
				return $file['type'];
		}
	}
	return '';
}
  