/*
Copyright (c) 2013-2014 Gustav Hartvigsson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "utils.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <sys/time.h>
#include <wchar.h>
#include <locale.h>

schar *
s_string_new (const schar * s) {
  if (s == NULL) {
    return NULL;
  }
  size_t s_len = strlen (s);
  assert (s_len > 0);
  schar * ret_val = s_malloc (s_len + 1);
  strcpy (ret_val, s);
  ret_val[s_len] = '\0';
  return ret_val;
}

schar *
s_string_new_fmt (const schar * format, ...) {
  schar * buffer = s_malloc (strlen (format) + 512);
  schar * ret_val = NULL;
  va_list args;
  va_start(args, format);
  vsprintf (buffer, format, args);
  ret_val = s_string_new (buffer);
  va_end(args);
  s_free (buffer);
  return ret_val;
}

schar *
s_string_new_with_len (const schar * s, size_t len) {
  schar * ret_val = s_malloc (len + 1);
  ret_val[len + 1] = 0x0;
  strncpy (ret_val, s, len);
  return ret_val;
}

schar *
s_current_time (void) {
  schar * ret_val = s_malloc (21);
  time_t t = time (NULL);
  strftime (ret_val, 21, "%F %T", localtime (&t));
  return ret_val;
}

schar *
s_current_time_full (void) {
   schar * ret_val = s_malloc (32);
   schar fmt[32];
   time_t t = time (NULL);
   struct timeval tv;
   gettimeofday (&tv, NULL);
   strftime (fmt, 50,"%Y-%m-%dT%H:%M:%S.%%03u%z", localtime (&t));
   snprintf(ret_val, 50, fmt, tv.tv_usec);
   return ret_val;
}

sboolean
s_string_is_equal (const schar * a, const schar * b) {
  if (strcmp (a, b)){
    return FALSE;
  } else {
    return TRUE;
  }
}

size_t
s_string_len (const schar * str) {
  return strlen (str);
}

size_t
s_ustring_len (const suchar * us) {
  if (!us) {
    return 0;
  }
  size_t ret_val = 0;
  suchar * tmp = (suchar *)us;
  while (*tmp) {
    ret_val++;
    us++;
  }
  return ret_val;
}

/******************************************************************************/
schar *
s_ustring_to_string (const suchar * us) {
  schar * buffer;
  schar * resized;
  size_t bufpos = 0;
  mbstate_t mbstate;
  memset (&mbstate, 0, sizeof (mbstate));
  
  /* Thanks to Florian Philipp.
   * Thread: https://plus.google.com/u/0/+GustavHartvigsson/posts/4Wk7La1kWPP
   *
   * This is an adaptation of the original code to work with our suchar stuffs.
   */
  
  /* Save locale */
  schar * saved_locale;
  {
    schar * old_locale;
    size_t old_locale_len;
    old_locale = setlocale (LC_ALL, NULL);
    old_locale_len = strlen (old_locale) + 1;
    saved_locale = s_malloc (sizeof (char *) * old_locale_len);
    memcpy (saved_locale, old_locale, old_locale_len);
    /* set locale */
    setlocale (LC_ALL, "C.utf8");
  }
  
  buffer = malloc (sizeof (char32_t) * 4);
  
  schar out[MB_CUR_MAX];
  for(size_t n = 0, buflen = 4, bufpos = 0;
        n < s_ustring_len (us);
        n++, buflen += MB_CUR_MAX) { /* could be: buflen *= 2 ?*/
    sint rc = c32rtomb(out, us[n], &mbstate);
    if(! (resized = s_realloc (buffer, buflen))) {
      goto err;
    }
    buffer = resized;
    for (sint i = 0; i < rc; ++i) {
      buffer[bufpos] = out[i];
      bufpos++;
    }
  }
  
    /* reset locale */
  setlocale (LC_ALL, saved_locale);
  
  /* shrink buffer to actually required size */
  if (! (resized = s_realloc (buffer, bufpos + 1)))
    goto err;
  
  
  return resized;
err:
  
  s_free(buffer);
  return NULL;
}

/******************************************************************************/
suchar *
s_string_to_ustring (const schar * str) {
  suchar * buffer;
  suchar * resized;
  size_t bufpos = 0;
  mbstate_t mbstate;
  memset (&mbstate, 0, sizeof (mbstate));
  
  suint slen = s_string_len (str);
  
  
  /* Addaptation of the code in s_wstring_to_string to make it convert
   * mb strings to char32_t strings.
   */
  
  /* Save locale */
  schar * saved_locale;
  {
    schar * old_locale;
    size_t old_locale_len;
    old_locale = setlocale (LC_ALL, NULL);
    old_locale_len = strlen (old_locale) + 1;
    saved_locale = s_malloc (sizeof (char *) * old_locale_len);
    memcpy (saved_locale, old_locale, old_locale_len);
    /* set locale */
    setlocale (LC_ALL, "C.utf8");
  }
  
  buffer = malloc (sizeof (char32_t) * 4);
  
  suchar * out = s_malloc (sizeof (suchar));
  for(size_t n = 0, buflen = 4, bufpos = 0;
        n < slen;
        buflen += 2) {
    sint rc = mbrtoc32(out, &str[n], slen ,&mbstate);
    n += rc; // Get next mb in string...?
    if(! (resized = s_realloc (buffer, buflen * sizeof (suchar)))){
      goto err;
    }
    buffer = resized;
    buffer[bufpos] = *out;
    bufpos++;
  }
  
  s_free (out);
  
  /* reset locale */
  setlocale (LC_ALL, saved_locale);
  
  /* shrink buffer to actually required size */
  if (! (resized = s_realloc (buffer, (bufpos + 1) * sizeof (suchar)))) {
    goto err;
  }
  
  
  return resized;
err:
  
  s_free(buffer);
  return NULL;
  
}

/******************************************************************************/
#if 0
/*
 * This should not be used. If you need to use this, uncomment it.
 * I am conveting to something more sane than wchar_t.
 */
schar *
s_wstring_to_string (const wchar_t * ws) {
  s_err_print ("Using depricated function: s_wstring_to_string ().\n"
               "Do not use s_wstring_to_string, as it is platform "
               "specific and may, or may not couse troubble.\n"
               "Use uchar strings instead of wchar_t strings, and "
               "use s_ustring_to_string instead of this.\n");
  
  size_t buflen;
  schar * buffer;
  schar * resized;
  size_t bufpos;
  mbstate_t mbstate;
  memset (&mbstate, 0, sizeof (mbstate));
  
  
  /* Save locale */
  schar * saved_locale;
  {
    schar * old_locale;
    size_t old_locale_len;
    old_locale = setlocale (LC_ALL, NULL);
    old_locale_len = strlen (old_locale) + 1;
    saved_locale = s_malloc (sizeof (char *) * old_locale_len);
    memcpy (saved_locale, old_locale, old_locale_len);
    /* set locale */
    setlocale (LC_ALL, "C.utf8");
  }
  
  /* Thanks to Florian Philipp.
   * Thread: https://plus.google.com/u/0/+GustavHartvigsson/posts/4Wk7La1kWPP
   *
   * to avoid parsing the string twice, we allocate memory speculatively
   * with exponential growth. Then we shrink it at the end.
   *
   * Alternative:  use
   * const wchar_t* tmp = ws;
   * size_t buflen = wcsrtombs(NULL, &tmp, 0, mbstate);
   * buffer = malloc(buflen);
   * wcsrtombs(buffer, &ws, 0, mbstate);
   * return buffer;
   */
  for (buflen = 4, buffer = NULL, bufpos = 0; ws; buflen *= 2) {
    size_t converted;
    if(! (resized = s_realloc (buffer, buflen)))
      goto err;
    buffer = resized;
    if((converted = wcsrtombs (buffer + bufpos, &ws, buflen - bufpos, &mbstate))
       == (size_t) -1)
      goto err;
    bufpos += converted;
  }
  
  /* reset locale */
  setlocale (LC_ALL, saved_locale);
  
  /* shrink buffer to actually required size */
  if (! (resized = s_realloc (buffer, bufpos + 1))) {
    goto err;
  }
  
  return resized;
err:
  
  s_free(buffer);
  return NULL;
}
#endif

/*
 * See: http://www.programmingsimplified.com/c/source-code/c-program-binary-search
 */
#define _INTERNAL_MAKE_BIN_SEARCH_FUNC(T) \
sboolean \
s_binary_search_##T ( T list[], size_t f, size_t l, T n) {\
  size_t first = f;\
  size_t last = l;\
  size_t middle = (first + last)/2;\
  \
  while (first <= last) {\
    if (SPrimeListLong[middle] < n) {\
     first = middle + 1;\
    } else if (list[middle == n]) {\
      return TRUE;\
    } else {\
      last = middle - 1;\
    }\
    middle = (first + last) / 2;\
  }\
  return FALSE;\
}

_INTERNAL_MAKE_BIN_SEARCH_FUNC(sbyte)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(subyte)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(sshort)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(sushort)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(sint)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(suint)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(slong)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(sulong)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(sfloat)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(sdouble)

_INTERNAL_MAKE_BIN_SEARCH_FUNC(squadruple)


/* ************************************************************************** 
 * Signal handlers
 * ************************************************************************** */
void
s_sig_segfault (int code) {
  if (code == SIGSEGV) {
    print_backtrace();
  }
}


