/*
*  Naamari - an AES/SHA-based manual file crypto-synchronizer for cloud transfers
*  Copyright (c) 2015-2017 Sunkware
*  Key FP = 6B6D C8E9 3438 6E9C 3D97  56E5 2CE9 A476 99EF 28F6
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*  See the GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*  ----------------------------------------------------------------
*  WWW:       sunkware.org
*  E-mail:    sunkware@gmail.com
*  ----------------------------------------------------------------
*/

#include "timework.h"

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


namespace cryptrav
{

namespace TIMESS
{


int            getFileModTime(QString absoluteFilePath, qint64* pSecsSinceEpoch)
{
 struct stat   fileStats;

 if (stat((const char *)absoluteFilePath.toUtf8().constData(), &fileStats) != 0) {
  return CTERR_FILE_STATS_UNAVAILABLE;
 }

 *pSecsSinceEpoch = fileStats.st_mtime;

 return CTERR_OK;
}

int            setFileModTime(QString absoluteFilePath, qint64 secsSinceEpoch)
{
 struct stat           fileStats;
 struct utimbuf        fileTimes;

 if (stat((const char *)absoluteFilePath.toUtf8().constData(), &fileStats) != 0) {
  return CTERR_FILE_STATS_UNAVAILABLE;
 }

 fileTimes.actime = fileStats.st_atime;
 fileTimes.modtime = secsSinceEpoch;

 if ( utime((const char *)absoluteFilePath.toUtf8().constData(), &fileTimes) != 0) {
  return CTERR_FILE_TIME_CANNOT_SET;
 }

 return CTERR_OK;
}


QString        strTime(qint64 secsSinceEpoch)
{
 return QDateTime::fromMSecsSinceEpoch(secsSinceEpoch * 1000).toString("yyyy.MM.dd, HH:mm:ss");
}

QString        strFileModTime(QString absoluteFilePath)
{
 qint64 modTime;

 if (getFileModTime(absoluteFilePath, &modTime) != CTERR_OK) {
  return QString("");
 }

 return strTime(modTime);
}



} // namespace "TIMESS"

} // namespace "cryptrav"
