///
/// @file cwg-shared.c
/// @authors k. headley
/// @date 03 mar 2020

/// Shared (cross-platform)  Carbon Waveglider (CWG) system functions and definitions

/// @sa doxygen-examples.c for more examples of Doxygen markup


/////////////////////////
// Terms of use
/////////////////////////
/*
 Copyright Information

 Copyright 2002-YYYY MBARI
 Monterey Bay Aquarium Research Institute, all rights reserved.

 Terms of Use

 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. You can access the GPLv3 license at
 http://www.gnu.org/licenses/gpl-3.0.html

 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
 (http://www.gnu.org/licenses/gpl-3.0.html)

 MBARI provides the documentation and software code "as is", with no warranty,
 express or implied, as to the software, title, non-infringement of third party
 rights, merchantability, or fitness for any particular purpose, the accuracy of
 the code, or the performance or results which you may obtain from its use. You
 assume the entire risk associated with use of the code, and you agree to be
 responsible for the entire cost of repair or servicing of the program with
 which you are using the code.

 In no event shall MBARI be liable for any damages, whether general, special,
 incidental or consequential damages, arising out of your use of the software,
 including, but not limited to, the loss or corruption of your data or damages
 of any kind resulting from use of the software, any prohibited use, or your
 inability to use the software. You agree to defend, indemnify and hold harmless
 MBARI and its officers, directors, and employees against any claim, loss,
 liability or expense, including attorneys' fees, resulting from loss of or
 damage to property or the injury to or death of any person arising out of the
 use of the software.

 The MBARI software is provided without obligation on the part of the
 Monterey Bay Aquarium Research Institute to assist in its use, correction,
 modification, or enhancement.

 MBARI assumes no responsibility or liability for any third party and/or
 commercial software required for the database or applications. Licensee agrees
 to obtain and maintain valid licenses for any additional third party software
 required.
 */

/////////////////////////
// Headers
/////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "cwg-shared.h"
#if defined(__PIC24FJ256GA106__) || defined(__PIC24FJ256GA606__) || defined(__PIC24FJ1024GA606__)
#include "ioserial.h"
#endif

/////////////////////////
// Macros
/////////////////////////

// These macros should only be defined for
// application main files rather than general C files
/*
 /// @def PRODUCT
 /// @brief header software product name
 #define PRODUCT "TBD_PRODUCT"

 /// @def COPYRIGHT
 /// @brief header software copyright info
 #define COPYRIGHT "Copyright 2002-YYYY MBARI Monterey Bay Aquarium Research Institute, all rights reserved."
 /// @def NOWARRANTY
 /// @brief header software terms of use
 #define NOWARRANTY  \
 "This program is distributed in the hope that it will be useful,\n"\
 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"\
 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"\
 "GNU General Public License for more details (http://www.gnu.org/licenses/gpl-3.0.html)\n"
 */

/////////////////////////
// Declarations
/////////////////////////

/////////////////////////
// Imports
/////////////////////////

/////////////////////////
// Module Global Variables
/////////////////////////
// debug print enable (set non-zero to enable DPRINT)
int g_dprint=0;
int g_vprint=0;
uint32_t g_xprint=0;
uint32_t g_mdebug_flags=0;

// time string buffer
char striso8601_mem[TIMESTAMP_STR_BYTES]={0};

/////////////////////////
// Function Definitions
/////////////////////////

int hex_show(byte *data, size_t len, int cols, int indent, bool show_ofs)
{

    int retval=-1;
    if(NULL!=data && len>0){
        int wbytes=0;
        byte *pd = data;
        int width = (cols>0 ? cols : 16);
        while(pd<(data+len)){
            if( ((pd-data)%width)==0){
                if(pd>data)
                    wbytes+=OUT_CTTY("\r\n");
                if(show_ofs){
                    unsigned long int ofs = (pd-data);
                   wbytes+=OUT_CTTY("%*s%08"FMT_XBP": ",indent,(indent>0?" ":""),ofs);
                }
            }
            wbytes+=OUT_CTTY("%02X ",*pd);
            pd++;
        }
        wbytes+=OUT_CTTY("\r\n");
        retval=wbytes;
    }
    return retval;
}

time_t parse_iso8601(const char *isotime, struct tm *rval)
{
    time_t retval=-1;
    if(NULL!=isotime){
        struct tm iso_tm={0};
        if(sscanf(isotime,"%4d-%2d-%2dT%2d:%2d:%2d",
                  &iso_tm.tm_year,&iso_tm.tm_mon,&iso_tm.tm_mday,
                  &iso_tm.tm_hour,&iso_tm.tm_min,&iso_tm.tm_sec)==6){
            iso_tm.tm_year-=1900;
            iso_tm.tm_mon-=1;
            retval = mktime(&iso_tm);
            if(NULL!=rval){
                memcpy(rval,&iso_tm,sizeof(struct tm));
            }
        }
    }
    return retval;
}

char *striso8601(char *dest, uint64_t timestamp, sys_iso8601_precision pflag)
{
    char *retval=NULL;

    time_t tt = U64_TIMESTAMP_SEC(timestamp);
#if defined(__PIC24FJ256GA106__) || defined(__PIC24FJ256GA606__) || defined(__PIC24FJ1024GA606__)
    struct tm *ptm=gmtime(&tt);
#elif defined(__unix__) || defined(__APPLE__) || defined(__CYGWIN__)
    struct tm stm={0},*ptm=&stm;
    gmtime_r(&tt, ptm);
#elif defined(__WIN32) || defined(__WIN64)
    struct tm stm={0},*ptm=&stm;
    gmtime_s(ptm, &tt);
#endif

    if(NULL!=dest){
        retval=dest;
    }else{
#ifdef STRISO8601_STATIC_MEM
        retval=striso8601_mem;
#elif defined(__PIC24FJ256GA106__) || defined(__PIC24FJ256GA606__) || defined(__PIC24FJ1024GA606__)
        // always use static buffer
        retval=striso8601_mem;
#else
        retval=(char *)malloc(TIMESTAMP_STR_BYTES);
#endif

        ZERO_MEM(retval,TIMESTAMP_STR_BYTES);
    }
    sprintf(retval,"%04u-%02u-%02uT%02u:%02u:%02u.%03lluZ",1900+ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday,ptm->tm_hour, ptm->tm_min, ptm->tm_sec,U64_TIMESTAMP_MSEC(timestamp));
    return retval;
}

int tokenize(char *src, char **dest, char *del, int ntok)
{
    int i=0;
    while(i<ntok){
        dest[i]=strtok((i==0?src:NULL),del);
        if(NULL==dest[i]){
            break;
        }
        i++;
    }
    return i;
}

byte crc8(byte *data, uint32_t len)
{
    uint8_t crc = CRC8_INIT;
    uint32_t i, j;
    for (i = 0; i < len; i++) {
        crc ^= data[i];
        for (j = 0; j < 8; j++) {
            if ((crc & 0x80) != 0){
                crc = (byte)((crc << 1) ^ CRC8_POLY);
            }else{
                crc <<= 1;
            }
        }
    }
    return crc;
}

int bytes_to_xstr(byte *src, char *dest, uint32_t slen, uint32_t dlen, uint32_t flags)
{
    int retval=0;
    if(NULL!=src && NULL!=dest ){
        byte *scur = src;
        char *dcur = dest;

        while( (dcur<(dest+dlen)) && scur<(src+slen)){
            char *fmt = ((flags&XFMT_UCASE)!=0 ? "%02X" : "%02x");
            retval+=sprintf(dcur,fmt,*scur);
            dcur+=2;
            scur++;
        }
        if( (flags&XFMT_CRC8)!=0 && ((dcur-dest) >= 3) ){
            byte crc=crc8((byte *)dest,strlen(dest));
            sprintf((dest+strlen(dest)),"*%02X",crc);
            retval+=3;
        }
    }
    return retval;
}