#include"myls.h"
#include<sys/stat.h>
#include<sys/types.h>
#include<pwd.h> /* struct passwd */
#include<grp.h> /* struct group */
#include<time.h>

void print_ls(int nfiles, struct dirent **showfiles, int m0de){
	struct stat file;	/* $man 2 stat */
	struct tm *machinetime; /* $man 3 localtime */

	/* Cada campo de la opcion larga [ls -l] */
	char permstring[11];	permstring[10]= '\0'; /* String de permisos */
	nlink_t nlinks;	/* numero de links */
	struct passwd *userdata; /* owner */
	struct group *groupdata; /* group owner */
	off_t fsize; /* tamano del archivo en bytes */
	char *dateformat= "%04d-%02d-%02d %02d:%02d "; /* Formato para imprimir la fecha */
	char *name;

	int k;
	if( (m0de == 2) || (m0de == 6) ){
	/* Si el modo es cualquier formatos largo, LONG=2 y LONG_ALL=6 */
		for(k=0; k < nfiles; k++){
		/* desde 0 hasta el numero de archivos a imprimir (nfiles) */
			name= showfiles[k]->d_name;
			/* name apunta al nombre del archivo actual */

			/*** OBTENER INFORMACION DEL ARCHIVO ***/
			stat(name, &file);
			/* stat() y mando resultados a la estructura file */
			nlinks= file.st_nlink;
			fsize= file.st_size;

			userdata= getpwuid(file.st_uid);
			/* obtengo el username por medio del UID */
			groupdata= getgrgid(file.st_gid);
			/* obtengo el groupname por medio del GID */

			machinetime= localtime(&file.st_mtime);
			/* Obtengo datos de fecha y hora del archivo */

			mode_string(file.st_mode, permstring);
			/* filemode.c de GNU/fileutils-4.1 contiene la funcion llamada mode_string() la cual recibe el modo (en octal) y el string de salida es enviado a permstring */

			/*** IMPRIMIENDO EL FORMATO LARGO  ***/

			fprintf(stdout, "%s ", permstring); /* permisos */
			fprintf(stdout, "%4u ", (unsigned int) nlinks); /* nlinks*/
			fprintf(stdout, "%s\t", userdata->pw_name); /* user */
			fprintf(stdout, "%s\t", groupdata->gr_name);/* grupo */
			fprintf(stdout, "%9u ", (unsigned int) fsize); /* tamano */
			fprintf(stdout, dateformat,
				machinetime->tm_year+YEARS_UTC,
				machinetime->tm_mon+1,
				machinetime->tm_mday,
				machinetime->tm_hour,
				machinetime->tm_min); /* la hora de ultima modificacion */
			fprintf(stdout, "%s\n", name);

			/*** FIN DE IMPRESION FORMATO LARGO ***/

			memset(&file, 0x00, sizeof(file));
			/* Vacio la estructura file, para que sea usada por el proximo archivo */
		}
	}
	else{	/* Si no, imprime los archivos en formato normal */
		for(k=0; k < nfiles; k++){
			if( (k != 0) && ((k % 7) == 0) )
				fprintf(stdout, "\n");

			name= showfiles[k]->d_name;
			fprintf(stdout, "%s\t", name);
		}

		fprintf(stdout, "\n");
	}
}
