/*
  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors

  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.
*/

/* cJSON minimal implementation for PX4 offline_task_manager */

#include "cJSON.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <float.h>
#include <math.h>

/* Parse text to find a number */
static const char *parse_number(cJSON *item, const char *num)
{
    double n = 0;
    double scale = 0;
    int subscale = 0;
    int signsubscale = 1;
    int sign = 1;

    if (*num == '-') {
        sign = -1;
        num++;
    }

    if (*num == '0') {
        num++;
    }

    if ((*num >= '1') && (*num <= '9')) {
        do {
            n = (n * 10.0) + (*num++ - '0');
        } while ((*num >= '0') && (*num <= '9'));
    }

    if ((*num == '.') && (num[1] >= '0') && (num[1] <= '9')) {
        num++;
        do {
            n = (n * 10.0) + (*num++ - '0');
            scale--;
        } while ((*num >= '0') && (*num <= '9'));
    }

    if ((*num == 'e') || (*num == 'E')) {
        num++;
        if (*num == '+') {
            num++;
        } else if (*num == '-') {
            signsubscale = -1;
            num++;
        }

        while ((*num >= '0') && (*num <= '9')) {
            subscale = (subscale * 10) + (*num++ - '0');
        }
    }

    n = sign * n * pow(10.0, (scale + (subscale * signsubscale)));

    item->valuedouble = n;
    item->valueint = (int)n;
    item->type = cJSON_Number;

    return num;
}

/* Parse string */
static const char *parse_string(cJSON *item, const char *str)
{
    const char *ptr = str + 1;
    char *ptr2;
    char *out;
    int len = 0;

    if (*str != '\"') {
        return NULL;
    }

    while ((*ptr != '\"') && *ptr) {
        if (*ptr++ == '\\') {
            ptr++;
        }
        len++;
    }

    out = (char *)malloc(len + 1);
    if (!out) {
        return NULL;
    }

    ptr = str + 1;
    ptr2 = out;

    while ((*ptr != '\"') && *ptr) {
        if (*ptr != '\\') {
            *ptr2++ = *ptr++;
        } else {
            ptr++;
            switch (*ptr) {
                case 'b': *ptr2++ = '\b'; break;
                case 'f': *ptr2++ = '\f'; break;
                case 'n': *ptr2++ = '\n'; break;
                case 'r': *ptr2++ = '\r'; break;
                case 't': *ptr2++ = '\t'; break;
                default: *ptr2++ = *ptr; break;
            }
            ptr++;
        }
    }

    *ptr2 = '\0';
    item->valuestring = out;
    item->type = cJSON_String;

    return ptr + 1;
}

static const char *skip(const char *in)
{
    while (in && *in && ((unsigned char)*in <= 32)) {
        in++;
    }
    return in;
}

/* Forward declarations */
static const char *parse_value(cJSON *item, const char *value);
static const char *parse_array(cJSON *item, const char *value);
static const char *parse_object(cJSON *item, const char *value);

/* Parse an object */
static const char *parse_object(cJSON *item, const char *value)
{
    cJSON *child = NULL;
    cJSON *new_item = NULL;

    if (*value != '{') {
        return NULL;
    }

    item->type = cJSON_Object;
    value = skip(value + 1);

    if (*value == '}') {
        return value + 1;
    }

    while (1) {
        new_item = (cJSON *)malloc(sizeof(cJSON));
        if (!new_item) {
            return NULL;
        }
        memset(new_item, 0, sizeof(cJSON));

        if (!child) {
            item->child = new_item;
        } else {
            child->next = new_item;
            new_item->prev = child;
        }
        child = new_item;

        /* Parse name */
        value = skip(parse_string(child, skip(value)));
        if (!value) {
            return NULL;
        }
        child->string = child->valuestring;
        child->valuestring = NULL;

        value = skip(value);
        if (*value != ':') {
            return NULL;
        }
        value = skip(parse_value(child, skip(value + 1)));
        if (!value) {
            return NULL;
        }

        if (*value == '}') {
            return value + 1;
        }

        if (*value != ',') {
            return NULL;
        }
        value = skip(value + 1);
    }
}

/* Parse an array */
static const char *parse_array(cJSON *item, const char *value)
{
    cJSON *child = NULL;
    cJSON *new_item = NULL;

    if (*value != '[') {
        return NULL;
    }

    item->type = cJSON_Array;
    value = skip(value + 1);

    if (*value == ']') {
        return value + 1;
    }

    while (1) {
        new_item = (cJSON *)malloc(sizeof(cJSON));
        if (!new_item) {
            return NULL;
        }
        memset(new_item, 0, sizeof(cJSON));

        if (!child) {
            item->child = new_item;
        } else {
            child->next = new_item;
            new_item->prev = child;
        }
        child = new_item;

        value = skip(parse_value(child, skip(value)));
        if (!value) {
            return NULL;
        }

        if (*value == ']') {
            return value + 1;
        }

        if (*value != ',') {
            return NULL;
        }
        value = skip(value + 1);
    }
}

/* Parse a value */
static const char *parse_value(cJSON *item, const char *value)
{
    if (!value) {
        return NULL;
    }

    if (!strncmp(value, "null", 4)) {
        item->type = cJSON_NULL;
        return value + 4;
    }

    if (!strncmp(value, "false", 5)) {
        item->type = cJSON_False;
        return value + 5;
    }

    if (!strncmp(value, "true", 4)) {
        item->type = cJSON_True;
        item->valueint = 1;
        return value + 4;
    }

    if (*value == '\"') {
        return parse_string(item, value);
    }

    if ((*value == '-') || ((*value >= '0') && (*value <= '9'))) {
        return parse_number(item, value);
    }

    if (*value == '[') {
        return parse_array(item, value);
    }

    if (*value == '{') {
        return parse_object(item, value);
    }

    return NULL;
}

/* Public parse function */
cJSON *cJSON_Parse(const char *value)
{
    cJSON *c = (cJSON *)malloc(sizeof(cJSON));
    if (!c) {
        return NULL;
    }
    memset(c, 0, sizeof(cJSON));

    if (!parse_value(c, skip(value))) {
        cJSON_Delete(c);
        return NULL;
    }

    return c;
}

/* Delete cJSON object */
void cJSON_Delete(cJSON *c)
{
    cJSON *next;
    while (c) {
        next = c->next;
        if (c->child) {
            cJSON_Delete(c->child);
        }
        if (c->valuestring) {
            free(c->valuestring);
        }
        if (c->string) {
            free(c->string);
        }
        free(c);
        c = next;
    }
}

/* Get object item */
cJSON *cJSON_GetObjectItem(const cJSON * const object, const char * const string)
{
    cJSON *c = object ? object->child : NULL;
    while (c) {
        if (c->string && !strcmp(c->string, string)) {
            return c;
        }
        c = c->next;
    }
    return NULL;
}

/* Get array item */
cJSON *cJSON_GetArrayItem(const cJSON *array, int index)
{
    cJSON *c = array ? array->child : NULL;
    while (c && index > 0) {
        c = c->next;
        index--;
    }
    return c;
}

/* Get array size */
int cJSON_GetArraySize(const cJSON *array)
{
    int size = 0;
    cJSON *c = array ? array->child : NULL;
    while (c) {
        size++;
        c = c->next;
    }
    return size;
}

/* Get string value */
const char *cJSON_GetStringValue(const cJSON * const item)
{
    if (!item || !(item->type & cJSON_String)) {
        return NULL;
    }
    return item->valuestring;
}

/* Get number value */
double cJSON_GetNumberValue(const cJSON * const item)
{
    if (!item || !(item->type & cJSON_Number)) {
        return 0;
    }
    return item->valuedouble;
}

/* Type check functions */
int cJSON_IsObject(const cJSON * const item)
{
    return item && (item->type == cJSON_Object);
}

int cJSON_IsArray(const cJSON * const item)
{
    return item && (item->type == cJSON_Array);
}

int cJSON_IsString(const cJSON * const item)
{
    return item && (item->type == cJSON_String);
}

int cJSON_IsNumber(const cJSON * const item)
{
    return item && (item->type == cJSON_Number);
}

int cJSON_IsBool(const cJSON * const item)
{
    return item && ((item->type == cJSON_True) || (item->type == cJSON_False));
}
