/* Copyright 2002 Tematic Ltd
 *
 * 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.
 */
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <locale.h>

#include "dbox.h"

#include "Options.h"
#include "dboxlong.h"

#ifdef USE_COMMAS
static void cvtlong(char *out, uint64_t num)
{
    struct lconv *l = localeconv();
    char buffer[128];
    char buffer2[128];
    char *p = buffer2 + sizeof buffer2;
    char *p2;
    const char *sep = l->thousands_sep;
    const char *group = l->grouping;
    int seplen = strlen(sep);
    int n;

    n = sprintf(buffer, "%ju", num);
    p2 = buffer + n - 1;

    n = *group;
    *--p = '\0';

    while (p2 >= buffer)
    {
        if (n != CHAR_MAX) n--;
        if (n < 0)
        {
            memcpy(p-seplen, sep, seplen);
            p-=seplen;
            n = *++group;
            if (n == 0)
                n = *--group;
            if (n != CHAR_MAX) n--;
        }
        *--p = *p2--;
    }
    strcpy(out, p);
}
#else
#define cvtlong(buf, n) snprintf(buf, "%ju", n)
#endif

void dbox_setlongnumeric(dbox d, dbox_field f, uint64_t n)
{
    char buf[128];

    cvtlong(buf, n);

    dbox_setfield(d, f, buf);
}