/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "MvPath.hpp"
#include "UtilitiesC.h"

static Cached user_dir = getenv("METVIEW_USER_DIRECTORY");
static Cached tmp_dir  = getenv("METVIEW_TMPDIR");
static Cached metv_dir = getenv("METVIEW_DIR_SHARE");

string
GetUserDirectory()
{
    return (const char*)user_dir;
}

Cached
MakeUserPath(const Cached& name)
{
// FII0710 I think this code is not correct. It should try
// to build an absolute path taking into consideration the
// relative part of the path "../"  Alternatively, leave
// the relative part of the path as it is.
#if 0
  // Strip off any relative part of the name "../.. etc"
  // to try to build a correct absolute path.
  bool found = false;
  const char *cptr = name;
  int i;

  if ( strlen(name) > 3 )
    {
      for ( i = strlen(name)-1; i >=2; i-- )
	{
	  if ( name[i] == '/' && name[i-1] == '.' && name[i-2] == '.' )
	    {
	      found = true;
	      break;
	    }
	}
    }

  if ( found )
    cptr += i;

  Cached fname = user_dir + (Cached)"/" + Cached(cptr);
#endif

  Cached fname = user_dir + (Cached)"/" + name;

  return fname;
}

string
MakeUserDefPath(const char* name, bool absolutePath)
{
    string fname;
    if ( absolutePath )
        fname += (const char*)user_dir;

    fname += "/System/Defaults/";
    fname += name;

    return fname;
}

string
MakeUserPrefPath(const char* name)
{
	string fname = (const char*)user_dir;
	fname += "/System/Preferences/";
	fname += name;

	return fname;
}

string
MakeSystemEtcPath(const string& name)
{
	string fname = (const char*)metv_dir + string("/etc/") + name;

	return fname;
}

string
MakeTmpPath(const char* name)
{
	string tmp = (const char*)tmp_dir;
	tmp += '/';
	tmp += name;

	return tmp;
}

Cached
MakeFilePath (const char* reqName )
{
	Cached path = user_dir + Cached("/") + Cached ( dirname ( reqName ));

return path;
}

const char*
MakeIconName ( const char* path, const char* iconPrefix )
{
	// The new icon name is the next on the list
	return UtProgressiveName2 ( path, iconPrefix );
}

Cached
MakePrinterFileName ( const Cached& path, const Cached& fileName )
{
	Cached newName;

	if ( fileName == (Cached) "" )
		newName = path + "PlotFile";
	else
	        newName = fileName;

return newName;
}

Cached
MakeTmpName ( const Cached& iconPrefix )
{
	char* p = UtRandomName (tmp_dir, iconPrefix );
	Cached newName = Cached ( p );
	free( p );
return newName;
}

// Create description file in METVIEW_USER_DIRECTORY
// (so that GenApp knows that kind of file it is)
const char*
MakeIconDescriptionName(const char* fileName )
{
	// Create the definition file name
	string defFileName = dirname( fileName);
	defFileName += "/.";
	defFileName += mbasename ( fileName );

	return defFileName.c_str();
}

Cached
MakeIconPath ( const char* iconName )
{

	Cached iconPath = metv_dir + Cached("/icons/") + Cached ( iconName ) +
		          Cached (".icon");
return iconPath;
}

// -- FUNCTION : FileCanBeOpened
//
// -- PURPOSE:   Tests if a file can be opened
//
// -- INPUT  :   filename and mode
//
// -- OUTPUT :   true/false

bool
FileCanBeOpened(const char* filename, const char* mode)
{
	FILE *fp;

	// Can we open it in the desired mode ?
	if ((fp = fopen(filename,mode)) != 0)
	{
		fclose (fp);
		return true;
	}

return false;
}

// -- FUNCTION : FileHasValidSize
//
// -- PURPOSE:   Tests if a file has size > 0
//
// -- INPUT  :   filename
//
// -- OUTPUT :   true/false

bool
FileHasValidSize(const char* filename )
{

	struct stat buf;

	// Can we reach the file ?
	if ( stat ( filename, &buf ) != 0 )
		return false;

	// Does it have non-zero size ?
	if ( buf.st_size == 0 )
		return false;

return true;
}

string
MakeProcessName (const char* name)
{
	// Build a process name according to the process id
	char buf[64];
	sprintf(buf,"%ld",(long)getpid());

	string fname(name);
	fname.append(buf);

	return fname;
}

string
FullPathName( const char* filename )
{
	string fullPath( filename );
	if( *filename != '/' )
	{
	   const char* pwd = getenv( "PWD" );
	   //std::cout << "PWD = " << pwd << std::endl;
	   fullPath = string( pwd ) + string( "/" ) + fullPath;
	   //std::cout << "full path = " << fullPath << std::endl;
	}
	return fullPath;
}
