//
// FileManager.cpp
//

#include <sys/stat.h>
#include <direct.h>

#define DBG_LEVEL 0
#include "Raym/Log.h"
#include "Raym/Raym.h"


namespace Raym
{

DEFINE_STATIC_MUTEX(mutex_);
static FileManager *defaultManager_ = NULL;

FileManager::FileManager()
{
    DebugLog2("FileManager::FileManager()");
}

FileManager::~FileManager()
{
    DebugLog2("FileManager::~FileManager()");
}

FileManager *FileManager::defaultManager()
{
    DebugLog2("FileManager::defaultManager()");

    mutex_.lock();
    if (defaultManager_ == NULL)
    {
        defaultManager_ = new FileManager();
        ((Object *)defaultManager_)->init();
        ((Object *)defaultManager_)->autorelease(true);
    }
    mutex_.unlock();

    return defaultManager_;
}

bool FileManager::fileExistsAtPath(String *path, bool *isDirectory)
{
    DebugLog2("FileManager::fileExistsAtPath(path,isDirectory)");

    bool result = false;
    if (path != NULL)
    {
#ifdef _WIN32
        struct __stat64 buffer;
        if (_stat64(path->cString(), &buffer) == 0)
        {
            result = true;
            if (isDirectory != NULL)
            {
                *isDirectory = ((buffer.st_mode & _S_IFDIR) == _S_IFDIR);
            }
        }
#else
#endif
    }
    return result;
}

bool FileManager::fileExistsAtPath(const char *path, bool *isDirectory)
{
    DebugLog2("FileManager::fileExistsAtPath(path,isDirectory)");

    bool result = false;
    if ((path != NULL) && (isDirectory != NULL))
    {
        result = fileExistsAtPath(String::stringWithUTF8String(path), isDirectory);
    }
    return result;
}

bool FileManager::removeItemAtPath(String *path, Error **error)
{
    DebugLog2("FileManager::removeItemAtPath()");

    bool result = false;
    if (path != NULL)
    {
        bool isDir = false;
        if (fileExistsAtPath(path, &isDir))
        {
            if (isDir)
            {
                result = (_rmdir(path->cString()) == 0);
            }
            else
            {
                result = (remove(path->cString()) == 0);
            }
        }
    }
    return result;
}

const char *FileManager::className()
{
    return "FileManager";
}

} // Raym
