#define BOOST_TEST_MAIN

#include <boost/test/unit_test.hpp>

#include "DataStorage/IDataStorage.h"
#include "common/Buffer.h"

#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "../src/DataStorage/posix/DataStorageDefs.h"
#include "commontypes.h"
#include <errno.h>

#include "iostream"

const char* const c_testProfile = "TestProfile";
const char* const c_testPrivateDataPath = "/tmp/Funambol/DMClient/DataStorage";

using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_DataStorage;

bool isFile(const String& path)
{
    struct stat st;
    bool res = (lstat(path.c_str(), &st) == 0);
    if (res)
    {
        res = false;
        if (S_ISREG(st.st_mode))
        {
            res = true;
        }
    }
    return res;
}

bool isPath(const String& path)
{
    struct stat st;
    bool res = (lstat(path.c_str(), &st) == 0);
    if (res)
    {
        res = false;
        if (S_ISDIR(st.st_mode))
        {
            if(  !(
                ((path[path.length()-2] == '/') && (path[path.length()-1] == '.'))
                ||
                ((path[path.length()-3] == '/') && (path[path.length()-2] == '.') && (path[path.length()-1] == '.'))
                )
               )
            {
                res = true;
            }
        }
    }
    return res;
}

bool deleteDirRecursive(const String& base)
{
    bool res = true;
    DIR* dir_handle = opendir(base.c_str());
    if (dir_handle)
    {
        struct dirent* entry_info;
        String entry_path;
        while ( (entry_info = readdir(dir_handle)) != 0 )
        {
            entry_path.append(base).append(c_pathSeparatorStr).append(entry_info->d_name);
            if (isPath(entry_path))
            {
                // try delete
                if (rmdir(entry_path.c_str()) != 0)
                {
                    // if failed try recursive
                    res = res && deleteDirRecursive(entry_path);
                }
            }
            else if (isFile(entry_path))
            {
                res = res && ((unlink(entry_path.c_str()) == 0) || (errno == ENOENT));
            }
        }
        closedir(dir_handle);
        res = true;
    }
    return res;
}

NS_DM_Client::NS_DataStorage::IDataStorage* S_dataStorage = 0;

class InitDataStorage
{
public:
	InitDataStorage()
	{
		S_dataStorage = NS_DM_Client::NS_DataStorage::CreateDataStorage(c_testProfile, c_testPrivateDataPath);
	}

	~InitDataStorage()
	{
		S_dataStorage->Release();
	}
};

BOOST_GLOBAL_FIXTURE(InitDataStorage);

BOOST_AUTO_TEST_SUITE(SuiteDataStorage)

BOOST_AUTO_TEST_CASE(CreateDataStorageInstance)
{
    bool res = false;
    IDataStorage* ds = CreateDataStorage(c_testProfile, c_testPrivateDataPath);
    if (ds)
    {
        res = true;
        ds->Release();
    }

	std::cout << "test case: CreateDataStorageInstance. res: " << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}

BOOST_AUTO_TEST_CASE(SavePrivateDataFromVoid)
{
    bool res = false;
    if (S_dataStorage)
    {
        const char* str_data = "private data from void works !!!";
        res = S_dataStorage->SavePrivateData("my_data/subdata/data/from_void", str_data, strlen(str_data));
    }

    std::cout << "test case: SavePrivateDataFromVoid. res: " << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}

BOOST_AUTO_TEST_CASE(SavePrivateDataFromBuffer)
{
    bool res = false;
    if (S_dataStorage)
    {
        Buffer buff;
        const char* str_data = "private data from buffer works !!!";
        buff.Allocate(34);
        memcpy(buff.GetPointer(), str_data, strlen(str_data));
        res = S_dataStorage->SavePrivateData("my_data/subdata/data/from_buffer", buff);
    }

    std::cout << "test case: SavePrivateDataFromBuffer. res: " << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}

BOOST_AUTO_TEST_CASE(LoadPrivateData)
{
    bool res = false;
    if (S_dataStorage)
    {
        Buffer buff;
        res = S_dataStorage->LoadPrivateData("my_data/subdata/data/from_buffer", buff);
    }

    std::cout << "test case: LoadPrivateData. res: " << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}

//--------------------------------------------------------------------------------
// new tests

BOOST_AUTO_TEST_CASE(CheckPrivateDataExist)
{
	bool res = false;
	if (S_dataStorage)
	{
		res = S_dataStorage->Exist("./my_data/subdata/data");
	}

	std::cout << "test case: CheckPrivateDataExist. res: "  << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}

BOOST_AUTO_TEST_CASE(CheckGetChildrenInterface)
{
	bool res = false;
	if (S_dataStorage)
	{
		Buffer buff;
		const char* str_data = "private data from buffer works !!!";
		buff.Allocate(34);
		memcpy(buff.GetPointer(), str_data, strlen(str_data));
		
		res = S_dataStorage->SavePrivateData("./my_data/subdata/data1/from_buffer", buff);
		res &= S_dataStorage->SavePrivateData("./my_data/subdata/data2/from_buffer", buff);
		res &= S_dataStorage->SavePrivateData("./my_data/subdata/data3/from_buffer", buff);
		res &= S_dataStorage->SavePrivateData("./my_data/subdata/data4/from_buffer", buff);

		if (res)
		{
			StringArray childs;
			res = S_dataStorage->GetChildList("./my_data/subdata", childs);
			if (res)
			{
				res = (childs.size() == 5);
				if (res)
				{
					res = (childs[0].compare("data") == 0);
					res &= (childs[1].compare("data1") == 0);
					res &= (childs[2].compare("data2") == 0);
					res &= (childs[3].compare("data3") == 0);
					res &= (childs[4].compare("data4") == 0);
				}
			}
		}
	}

	std::cout << "test case: CheckGetChildrenInterface. res: "  << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}


//--------------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(RemovePrivateData)
{
    bool res = false;
    if (S_dataStorage)
    {
        Buffer buff;
        if (S_dataStorage->LoadPrivateData("./my_data/subdata/data/from_buffer", buff))
        {
            res = S_dataStorage->RemovePrivateData("./my_data/subdata/data/from_buffer");
			if (res)
			{
				res = !(S_dataStorage->LoadPrivateData("./my_data/subdata/data/from_buffer", buff));
			}
		}
        else
        {
            res  = true;
        }
    }

    std::cout << "test case: RemovePrivateData. res: "  << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}

BOOST_AUTO_TEST_CASE(GetPrivateDataSize)
{
    bool res = false;
    if (S_dataStorage)
    {
        Buffer buff;
        const char* str_data = "private data from buffer works !!!";
        buff.Allocate(34);
        memcpy(buff.GetPointer(), str_data, strlen(str_data));
        res = S_dataStorage->SavePrivateData("my_data/subdata/data/from_buffer", buff);

        size_t data_size = 0;
        res = S_dataStorage->GetPrivateDataSize("my_data/subdata/data/from_buffer", data_size);

    	BOOST_CHECK( data_size == strlen(str_data) );
    }

    std::cout << "test case: GetPrivateDataSize. res: " << (res ? "success" : "failed") << std::endl;
	BOOST_CHECK( res == true );
}

BOOST_AUTO_TEST_CASE(ClearTestTemporaryData)
{
    // need delete path where tests write
    bool res = deleteDirRecursive((String)c_testPrivateDataPath + c_pathSeparatorStr + c_testProfile);
    std::cout << "test case: ClearTestTemporaryData. res: " << (res ? "success" : "failed") << std::endl;
    BOOST_CHECK( res == true );
}

BOOST_AUTO_TEST_SUITE_END()
