#include "StdAfx.h"
#include "utiles_def.h"
#include "dir_manager.h"
#include "_error.h"
#include "StrArray.h"
#include <direct.h>

#include <winver.h>
//****************************************************************

Cdir_manager::Cdir_manager(void)
{
	dir_exe[0]=dir_datos[0]=dir_log[0]=dir_work[0]=path_conf[0]=dir_ejecucion[0]=path_ejecutable[0]=0;
}
//****************************************************************
Cdir_manager::~Cdir_manager(void)
{
}
//****************************************************************
BOOL Cdir_manager::rellena_dirs_ejecucion()
{
	//char *st;
	BOOL res=TRUE;
	if (!_getcwd(dir_ejecucion, sizeof(dir_ejecucion)))
	{
		res= FALSE;
		dir_ejecucion[0]=0;
	}
	if(!GetModuleFileName(NULL,path_ejecutable,sizeof(path_ejecutable)))

	{
		path_ejecutable[0]=0;
		res=FALSE; 
	}
	return res;
}
//****************************************************************
void Cdir_manager::absoluta( char *ruta )
{
	char aux[256];
	if (strstr(ruta,D_WORK))
	{
		strcpy(aux,dir_work);
		strcat(aux,&ruta[strlen(D_WORK)]);
		strcpy(ruta,aux);
		return;
	}
	if (strstr(ruta,D_DAT))
	{
		strcpy(aux,dir_datos);
		strcat(aux,&ruta[strlen(D_DAT)]);
		strcpy(ruta,aux);
		return;
	}
	if (strstr(ruta,D_LOG))
	{
		strcpy(aux,dir_log);
		strcat(aux,&ruta[strlen(D_LOG)]);
		strcpy(ruta,aux);
		return;
	}
	if (strstr(ruta,D_APP))
	{
		strcpy(aux,dir_exe);
		strcat(aux,&ruta[strlen(D_APP)]);
		strcpy(ruta,aux);
		return;
	}
	if (strstr(ruta,P_CONG))
	{
		strcpy(ruta,P_CONG);
		return;
	}
}
//*******************************************************************************************
BOOL Cdir_manager::lee_reg( char* clave, C_error *er )
{
	HKEY  hKey1; 
	long   lRetCode,l2;
	//abrimos clave----------------------------------------
	lRetCode = RegOpenKeyEx ( HKEY_CURRENT_USER,clave, 0, KEY_READ | KEY_SET_VALUE,&hKey1); 

	if (lRetCode != ERROR_SUCCESS)
	{
		if(er)
		{
			er->pon_win("lee_reg");
		}
		return FALSE;
	}
		

	l2 = 256;
	//leemos carpeta
	RegQueryValueEx(hKey1,"dir",0,NULL,(LPBYTE) dir_work,(LPDWORD) &l2); 
	//cerramos clave------------------------------------
	RegCloseKey( hKey1);

	//configuramos rutas--------------------------------
	sprintf(dir_log,"%s\\log",dir_work);
	sprintf(dir_exe,"%s\\exe",dir_work);
	sprintf(dir_datos,"%s\\datos",dir_work);
	sprintf(path_conf,"%s\\conf.ini",dir_work);
	//ponemos log---------------------------------------
	return(TRUE);
}
//*******************************************************************************************
void Cdir_manager::relativa( char *ruta )
{
	char aux[256];
	if (dir_work[0]&&strstr(ruta,dir_work))
	{
		strcpy(aux,D_WORK);
		strcat(aux,&ruta[strlen(dir_work)]);
		strcpy(ruta,aux);
		return;
	}
	if (dir_datos[0]&&strstr(ruta,dir_datos))
	{
		strcpy(aux,D_DAT);
		strcat(aux,&ruta[strlen(dir_datos)]);
		strcpy(ruta,aux);
		return;
	}
	if (dir_log[0]&&strstr(ruta,dir_log))
	{
		strcpy(aux,D_LOG);
		strcat(aux,&ruta[strlen(dir_log)]);
		strcpy(ruta,aux);
		return;
	}
	if (dir_exe[0]&&strstr(ruta,dir_exe))
	{
		strcpy(aux,D_APP);
		strcat(aux,&ruta[strlen(dir_exe)]);
		strcpy(ruta,aux);
		return;
	}
	if (path_conf[0]&& strcmp(ruta,path_conf)==0)
	{
		strcpy(ruta,P_CONG);
		return;
	}
}
//*******************************************************************************************
char* Cdir_manager::dir_anterior( char*dir )
{
	int n=(int)strlen(dir);
	for (int i=n-1;i>0;i--)
	{
		if (dir[i]=='\\')
		{
			dir[i]=0;
			break;
		}
	}
	return dir;
}
//*******************************************************************************************
char* Cdir_manager::nombre_archivo( char *path,char*nombre )
{
	int n=(int)strlen(path);
	nombre[0]=0;
	for (int i=n-1;i>0;i--)
	{
		if (path[i]=='\\')
		{
			strcpy(nombre,&path[i+1]);
			break;
		}
	}
	if(!nombre[0])
		strcpy(nombre,path);
	return nombre;
}

BOOL Cdir_manager::listar( char* dir,StrArray *files,StrArray *dirs/*=NULL*/,BOOL recursivo/*=FALSE*/,C_error *er/*=NULL */,char *omite )
{
	BOOL poner_error=FALSE;
	BOOL p_c=FALSE;
	BOOL p_f=FALSE;
	char str[256];
	//int k;
	WIN32_FIND_DATA filedat;
	HANDLE hfile;

		
	if (!dir)
	{
		er->pon("listar","Puntero de listar nulo");
		return FALSE;
	}
	//vemos la info a recopilar--------------------------------------------
	if (er)
		poner_error=TRUE;
	if (dirs)
		p_c=TRUE;
	if(files)
		p_f=TRUE;

	strcpy(str,dir);
	if (str[strlen(str)-1] != '\\')
		strcat(str,"\\");
	strcat(str,"*.*");
	hfile = FindFirstFile(str,&filedat);

	if (hfile != INVALID_HANDLE_VALUE)//existe dir
	{
		// existe el dir
		do
		{
			if ((strcmp(filedat.cFileName,".")  != 0) &&
				(strcmp(filedat.cFileName,"..") != 0))
			{
				if (!omite||strcmp(omite,filedat.cFileName)!=0)
				{
					strcpy(str,dir);
					if (str[strlen(str)-1] != '\\')
						strcat(str,"\\");
					strcat(str,filedat.cFileName);
					if (filedat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
					{
						if (p_c)
						{
							dirs->add(str);
						}
						
						if(recursivo && !listar( str,files,dirs,recursivo,er,omite ))
						{
							FindClose(hfile);
							return FALSE;
						}
					}
					else if (p_f)
					{
						files->add(str);
					}
				}
			}
		} while (FindNextFile(hfile,&filedat));
		FindClose(hfile);

	}
	else
	{
		if (poner_error)
			er->pon_win("lista_file_dir");
		return FALSE;
	}
	return TRUE;
}
//*******************************************************************************************
BOOL Cdir_manager::listar_elementos( char *dir,StrArray *files,StrArray *dirs,C_error *er/*=NULL*/)
{
	return listar(dir,files,dirs,FALSE,er);
}
//*******************************************************************************************
BOOL Cdir_manager::lista_files( char *dir,StrArray *files,BOOL recursivo/*=FALSE*/,C_error *er/*=NULL*/,char *omite/*=NULL*/ )
{
	return listar(dir,files,NULL,recursivo,er,omite);
}
//*******************************************************************************************
char* Cdir_manager::extension_archivo( char *path )
{
	int n=(int)strlen(path)-1;
	while(n>=0)
	{
		if (path[n]=='.')
			return &path[n+1];
		n--;
		
	}
	return NULL;
}
//******************************************************************************************************************************************
BOOL Cdir_manager::crea_dir( char *path )
{
	char dir[MAX_PATH];
	int i, n;
	DWORD ftyp;
	n = (int)strlen(path);
	if (n<3)
		return TRUE;
	memcpy(dir, path, 3);
	for (i = 3; path[i]; i++)
	{
		if (i >= MAX_PATH)
			return FALSE;
		if (path[i] == '\\')
		{
			dir[i] = 0;
			//comprueba carpeta------------
			ftyp = GetFileAttributesA(dir);
			if ((ftyp == INVALID_FILE_ATTRIBUTES) && !CreateDirectory(dir, NULL))
				return FALSE;
		}
		else if ((path[i] == '.'))
			return TRUE;
		dir[i] = path[i];
	}
	dir[i] = 0;
	//comprueba carpeta------------
	ftyp = GetFileAttributesA(dir);
	if ((ftyp == INVALID_FILE_ATTRIBUTES) && !CreateDirectory(dir, NULL))
		return FALSE;
	return TRUE;
}
//*******************************************************************************************
BOOL Cdir_manager::borra_archivos( char *paht, char *ext, BOOL recursivo /*= FALSE*/ )
{
	StrArray lfiles;
	char *f;
	if(!Cdir_manager::listar(paht, &lfiles, NULL, recursivo ))
		return FALSE;
	for (int i = 0; i<lfiles.size(); i++)
	{
		f=lfiles.get((i));

		if(!ext || !strcmp(Cdir_manager::extension_archivo(f),ext))
			DeleteFile(f);
	}		
	return TRUE;
}
//*******************************************************************************************
char* Cdir_manager::cambia_extension_archivo( char *path, char *pathDst, char *newext )
{
	int n=(int)strlen(path);
	int i=0;
	char *c=strrchr(path,'.');
	while(n>i)
	{
		pathDst[i] = path[i];
		if (&path[i]==c)
		{
			i++;
			if(newext[0]=='.')
				strcpy(&pathDst[i],&newext[1]);
			else
				strcpy(&pathDst[i],newext);

			return pathDst;
		}		
		i++;

	}
	return NULL;
}

//*******************************************************************************************
char* Cdir_manager::getVersionFile( char *path, char *buf)
{
	DWORD  verHandle = 0;
	UINT   size      = 0;
	LPBYTE lpBuffer  = NULL;
	//DWORD  verSize   = GetFileVersionInfoSize( "D:\\desa\\BIN\\x64\\debug\\utiles.dll", &verHandle);
	buf[0]=0;

	char verData[1024];

	if (GetFileVersionInfo( path, verHandle, 1024, verData))
	{
		if (VerQueryValue(verData,"\\StringFileInfo\\%04x%04x\\FileDescription\\ProductName",(VOID FAR* FAR*)&lpBuffer,&size))
		{
			int ii = 0;
		}
		if (VerQueryValue(verData,"\\",(VOID FAR* FAR*)&lpBuffer,&size))
		{
			if (size)
			{
				VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)lpBuffer;
				if (verInfo->dwSignature == 0xfeef04bd)
				{

					// Doesn't matter if you are on 32 bit or 64 bit,
					// DWORD is always 32 bits, so first two revision numbers
					// come from dwFileVersionMS, last two come from dwFileVersionLS
					sprintf(buf, "%d.%d.%d.%d",
						( verInfo->dwFileVersionMS >> 16 ) & 0xffff,
						( verInfo->dwFileVersionMS >>  0 ) & 0xffff,
						( verInfo->dwFileVersionLS >> 16 ) & 0xffff,
						( verInfo->dwFileVersionLS >>  0 ) & 0xffff
						);
					return buf;
					
				}
			}
		}
	}
	return NULL;
}

//*******************************************************************************************
