/*
* Copyright 2009 Funambol, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* $Id$ */

#include "TimeStamp.h"
#include "Utils.h"

const size_t c_stampBuffer = 128;

namespace NS_DM_Client
{
    bool GetTimeStamp(String& stamp)
    {
        time_t ltime = time(NULL);

        bool res = false;

#if defined(PLATFORM_WINDOWS)
        tm Tm_tmp; 
        res = (localtime_s(&Tm_tmp, &ltime) == 0);
        tm* Tm = &Tm_tmp;
#else
        tm* Tm = localtime(&ltime); 
        res = (Tm != 0);
#endif

        if (res)
        {
            char stampBuffer[c_stampBuffer];
            memset(stampBuffer, '\0', c_stampBuffer);
            sprintf_s(stampBuffer, c_stampBuffer, "%04d-%02d-%02d %02d-%02d-%02d",
                Tm->tm_year + 1900,
                Tm->tm_mon,
                Tm->tm_mday,
                Tm->tm_hour,
                Tm->tm_min,
                Tm->tm_sec);

            stamp = stampBuffer;
        }
        else 
        {
            return false;
        }

        return true;
    }

    bool GetUniqueTimeStampForFileNaming(String& stamp)
    {
        static long index = 0; 

        if (GetTimeStamp(stamp))
        {
            char stampBuffer[c_stampBuffer];
            memset(stampBuffer, '\0', c_stampBuffer);
            sprintf_s(stampBuffer, c_stampBuffer, "%s___%06d", stamp.c_str(), ++index);
            stamp = stampBuffer;
            return true;
        }

        return false;
    }

}

