#include "pathcreator.h"

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdint.h>
#include <stdio.h>

PathCreator::PathCreator()
{

}

PathCreator::~PathCreator()
{

}

std::string PathCreator::GetCurPath()
{
    return m_current_path;
}
bool PathCreator::Mkdir(std::string dirName)
{
    uint32_t beginCmpPath = 0;
    uint32_t endCmpPath = 0;
    std::string fullPath = "";

    if('/' != dirName[0])
    {
        fullPath = getcwd(nullptr, 0);
        beginCmpPath = fullPath.size();
        fullPath = fullPath + "/" + dirName;
    }
    else
    {
        //Absolute path
        fullPath = dirName;
        beginCmpPath = 1;
    }
    if (fullPath[fullPath.size() - 1] != '/')
    {
        fullPath += "/";
    }
    endCmpPath = fullPath.size();

    //create dirs;
    for(uint32_t i = beginCmpPath; i < endCmpPath ; i++ )
    {
        if('/' == fullPath[i])
        {
            std::string curPath = fullPath.substr(0, i);
            if(access(curPath.c_str(), F_OK) != 0)
            {
                if(mkdir(curPath.c_str(), /*S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH*/0777) == -1)
                {
                    printf("mkdir(%s) failed\n", curPath.c_str());
                    return false;
                }
            }
        }
    }
    m_current_path=fullPath;
    return true;

}

bool PathCreator::CreateDatePath(std::string root, bool add_time)
{
    time_t tt;
    time( &tt );
    tt = tt + 8*3600;  // transform the time zone
    tm* t= gmtime( &tt );
    char buf[255]={0};
    if (add_time)
    {
        sprintf(buf, "%s/%d%02d%02d-%02d%02d%02d", root.c_str(),
                t->tm_year + 1900,
                t->tm_mon + 1,
                t->tm_mday,
                t->tm_hour,
                t->tm_min,
                t->tm_sec);
    }
    else
    {
        sprintf(buf, "%s/%d%02d%02d", root.c_str(),
                t->tm_year + 1900,
                t->tm_mon + 1,
                t->tm_mday);
    }
    return Mkdir(buf);
}
