/* Copyright (C) 2014 InfiniDB, Inc.

   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; version 2 of
   the License.

   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, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301, USA. */

/****************************************************************************
 * $Id: func_sec_to_time.cpp 2477 2011-05-12 16:07:35Z chao $
 *
 *
 ****************************************************************************/

#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;

#include "functor_str.h"
#include "functioncolumn.h"
#include "rowgroup.h"
#include "funchelpers.h"
#include "predicateoperator.h"
using namespace execplan;

#include "dataconvert.h"
#include "mcs_time.h"

#include "errorcodes.h"
#include "idberrorinfo.h"
#include "errorids.h"
using namespace logging;
namespace funcexp
{
CalpontSystemCatalog::ColType Func_sec_to_time::operationType(FunctionParm& /*fp*/,
                                                              CalpontSystemCatalog::ColType& resultType)
{
  return resultType;
}

string Func_sec_to_time::getStrVal(rowgroup::Row& row, FunctionParm& parm, bool& isNull,
                                   CalpontSystemCatalog::ColType& /*ct*/)
{
  int64_t val = 0;
  CalpontSystemCatalog::ColType curCt = parm[0]->data()->resultType();

  switch (parm[0]->data()->resultType().colDataType)
  {
    case execplan::CalpontSystemCatalog::BIGINT:
    case execplan::CalpontSystemCatalog::INT:
    case execplan::CalpontSystemCatalog::MEDINT:
    case execplan::CalpontSystemCatalog::TINYINT:
    case execplan::CalpontSystemCatalog::SMALLINT:
    case execplan::CalpontSystemCatalog::UBIGINT:
    case execplan::CalpontSystemCatalog::UINT:
    case execplan::CalpontSystemCatalog::UMEDINT:
    case execplan::CalpontSystemCatalog::UTINYINT:
    case execplan::CalpontSystemCatalog::USMALLINT:
    {
      val = parm[0]->data()->getIntVal(row, isNull);
      break;
    }

    case execplan::CalpontSystemCatalog::DOUBLE:
    case execplan::CalpontSystemCatalog::UDOUBLE:
      return datatypes::secToTimeWithUsec(parm[0]->data()->getDoubleVal(row, isNull));

    case execplan::CalpontSystemCatalog::FLOAT:
    case execplan::CalpontSystemCatalog::UFLOAT:
      return datatypes::secToTimeWithUsec((double)parm[0]->data()->getFloatVal(row, isNull));

    case execplan::CalpontSystemCatalog::LONGDOUBLE:
      return datatypes::secToTimeWithUsec((double)parm[0]->data()->getLongDoubleVal(row, isNull));

    case execplan::CalpontSystemCatalog::DECIMAL:
    case execplan::CalpontSystemCatalog::UDECIMAL:
    {
      IDB_Decimal dec = parm[0]->data()->getDecimalVal(row, isNull);
      return datatypes::secToTimeFromDecimal(dec, curCt.precision, curCt.scale);
    }

    case execplan::CalpontSystemCatalog::CHAR:
    case execplan::CalpontSystemCatalog::VARCHAR:
    case execplan::CalpontSystemCatalog::TEXT:
    {
      val = parm[0]->data()->getIntVal(row, isNull);
      break;
    }

    case execplan::CalpontSystemCatalog::TIME:
    {
      int64_t timeVal = parm[0]->data()->getTimeIntVal(row, isNull);
      uint32_t hour = (uint32_t)((timeVal >> 40) & 0xfff);
      uint32_t minute = (uint32_t)((timeVal >> 32) & 0xff);
      uint32_t second = (uint32_t)((timeVal >> 24) & 0xff);
      val = (int64_t)(hour * 3600 + minute * 60 + second);
      break;
    }

    case execplan::CalpontSystemCatalog::DATE:
    case execplan::CalpontSystemCatalog::DATETIME:
    case execplan::CalpontSystemCatalog::TIMESTAMP:
    {
      return "838:59:59";
      break;
    }

    case execplan::CalpontSystemCatalog::BLOB:
    case execplan::CalpontSystemCatalog::CLOB:
    case execplan::CalpontSystemCatalog::VARBINARY:
    case execplan::CalpontSystemCatalog::STRINT:
    case execplan::CalpontSystemCatalog::NUM_OF_COL_DATA_TYPE:
    case execplan::CalpontSystemCatalog::UNDEFINED:
    {
      val = parm[0]->data()->getIntVal(row, isNull);
      break;
    }

    default:
    {
      std::ostringstream oss;
      oss << "sec_to_time: datatype of "
          << execplan::colDataTypeToString(parm[0]->data()->resultType().colDataType);
      throw logging::IDBExcept(oss.str(), ERR_DATATYPE_NOT_SUPPORT);
    }
  }

  int64_t posVal = llabs(val);

  if (val > datatypes::TIME_MAX_WHOLE_SECONDS)
    return ("838:59:59");

  if (val < -datatypes::TIME_MAX_WHOLE_SECONDS)
    return ("-838:59:59");

  // Format the time
  uint32_t hour = 0;
  uint32_t minute = 0;
  uint32_t second = 0;

  hour = posVal / 3600;
  minute = (posVal - (hour * 3600)) / 60;
  second = posVal - (hour * 3600) - (minute * 60);

  const char* minus = "-";
  const char* nominus = "";

  const char* signstr = (val < 0) ? minus : nominus;

  char buf[32];  // actual string either 9 or 10 characters
  snprintf(buf, 32, "%s%02d:%02d:%02d", signstr, hour, minute, second);
  return buf;
}

int64_t Func_sec_to_time::getIntVal(rowgroup::Row& row, FunctionParm& parm, bool& isNull,
                                    CalpontSystemCatalog::ColType& op_ct)
{
  int64_t val = parm[0]->data()->getIntVal(row, isNull);

  if (val > datatypes::TIME_MAX_WHOLE_SECONDS)
    val = 8385959;
  else if (val < -datatypes::TIME_MAX_WHOLE_SECONDS)
    val = 4286581337LL;
  else
  {
    string time = getStrVal(row, parm, isNull, op_ct);
    size_t x = time.find(":");

    while (x < string::npos)
    {
      time.erase(x, 1);
      x = time.find(":");
    }

    char* ep = NULL;
    const char* str = time.c_str();
    errno = 0;
    val = strtoll(str, &ep, 10);
  }

  return val;
}

string Func_sec_to_time::getDigitStrVal(rowgroup::Row& row, FunctionParm& parm, bool& isNull,
                                        execplan::CalpontSystemCatalog::ColType& op_ct)
{
  string time = getStrVal(row, parm, isNull, op_ct);
  // getStrVal returns std::string by value (an owning copy), so time does not reference freed stack memory.
  // @infer-ignore USE_AFTER_LIFETIME
  time.erase(std::remove(time.begin(), time.end(), ':'), time.end());
  return time;
}

double Func_sec_to_time::getDoubleVal(rowgroup::Row& row, FunctionParm& parm, bool& isNull,
                                      execplan::CalpontSystemCatalog::ColType& op_ct)
{
  string digits = getDigitStrVal(row, parm, isNull, op_ct);
  return strtod(digits.c_str(), nullptr);
}

long double Func_sec_to_time::getLongDoubleVal(rowgroup::Row& row, FunctionParm& parm, bool& isNull,
                                               execplan::CalpontSystemCatalog::ColType& op_ct)
{
  string digits = getDigitStrVal(row, parm, isNull, op_ct);
  return strtold(digits.c_str(), nullptr);
}

execplan::IDB_Decimal Func_sec_to_time::getDecimalVal(rowgroup::Row& row, FunctionParm& parm, bool& isNull,
                                                      execplan::CalpontSystemCatalog::ColType& op_ct)
{
  IDB_Decimal d;

  string digits = getDigitStrVal(row, parm, isNull, op_ct);

  const int32_t scale = op_ct.scale;

  size_t dot = digits.find('.');
  string intPart = (dot == string::npos) ? digits : digits.substr(0, dot);
  string fracPart = (dot == string::npos) ? string() : digits.substr(dot + 1);

  // Render the fraction at exactly `scale` digits: resize truncates any extra
  // digits (no rounding) and zero-pads a shorter or absent fraction.
  fracPart.resize(scale, '0');

  int64_t tmpVal = strtoll((intPart + fracPart).c_str(), nullptr, 10);

  if (op_ct.isWideDecimalType())
    d.s128Value = tmpVal;
  else
    d.value = tmpVal;

  d.scale = scale;
  return d;
}

}  // namespace funcexp
