/*
 * oc_leaf.c
 *
 * Created: 9/24/2019 3:28:31 PM
 * 
 *  ######################################################################################################
 *  DISCLAIMER:
 *  OptConnect Management, LLC provides this documentation in support of its products for the internal use
 *  of its current and prospective customers. The publication of this document does not create any other
 *  right or license in any party to use any content contained in or referred to in this document and any
 *  modification or redistribution of this document is not permitted. While efforts are made to ensure
 *  accuracy, typographical and other errors may exist in this document. OptConnect Management, LLC reserves
 *  the right to modify or discontinue its products and to modify this and any other product documentation
 *  at any time.
 * 
 *  All OptConnect products are sold subject to its published Terms and Conditions and subject to any
 *  separate terms agreed with its customers. No warranty of any type is extended by publication of this
 *  documentation, including, but not limited to, implied warranties of merchantability, fitness for a
 *  particular purpose and non-infringement.
 * 
 *  OptConnect is a trademark, and OptConnect ema is a trademark, of OptConnect Management, LLC. All
 *  trademarks, service marks and similar designations referenced in this document are the property of
 *  their respective owners
 *  #######################################################################################################
 * 
 *  version: 1.0
 * 
 *  History:
 *  Version     Description                                     Date
 *  1.0         Initial Release                                 5/19/2020
 */ 

#include "oc_leaf.h"

static char device_id[100];

static char auth[100];
static int auth_len;

static char noop_buff[200];
static int noop_len;

static char leaf_build_message_buffer[1024];
static char leaf_resp_buff[1024];
static char leaf_content_type_buff[128];

void set_leaf_noop( void )
{
    noop_len = sprintf( noop_buff, "{\"deviceId\":\"%s\",\"message\":{\"messageType\": \"no-op\"}}", device_id );
}

void set_leaf_auth(char *realm, char *user, char *password) 
{
    int len;
    len=snprintf(auth, sizeof(auth), "Canopy-Auth-Req: %s:%s:%s", realm, user, password);
    auth_len = len;
}

int set_leaf_host( struct modem_at_context *context, char *host, unsigned char cntx_id ) 
{
    //int len;
    //len = snprintf(leaf_config, sizeof(leaf_config),
    //    "AT#HTTPCFG=2,\"%s\",443,0,\"\",\"\",1\r", host);
    //leaf_config_len = len;
    int at_st;
    at_st = emaModemAT_ConfigHTTP( context, 0, host, 443, 1, 15, cntx_id, HTTP_PCKT_SIZE_DEFAULT );
    return at_st;
}

int get_leaf_cmd( char *resp, char *cmd )
{
    char *p;

    // confirm this is cmd data
    p = strstr( resp, "\"command\"" );
    if ( p ) {
        // it is a cmd, strip out the cmd data
        p = strchr( p, ':' );
        strcpy( cmd, p+1 );
        return 1;
    }
    return 0;
}

int send_leaf_query( struct modem_at_context *context, unsigned char cntx_id, int data_len, int *resp_code, char *leaf_cmd )
{
    int at_st, cmd_st;
    unsigned short resp_len;

    //"AT#HTTPSND=2,0,\"/events/v2/\",%d,\"application/json\",\"%s\"\r",

    // send the leaf msg
    at_st = emaModemAT_HTTPPost(context, 0, 
                                         "/events/v2/", 
                                         "application/json", 
                                         auth, 
                                         leaf_build_message_buffer,
                                         data_len,
                                         leaf_content_type_buff,
                                         leaf_resp_buff,
                                         &resp_len,
                                         resp_code );
    if ( at_st == MOD_AT_ST_SUCCESS ) {
        // check the resp code
        if ( *resp_code == 200 ) {
            if ( resp_len > 16 ) {
                // response has cmd data, process it
                cmd_st = get_leaf_cmd( leaf_resp_buff, leaf_cmd );
                if ( cmd_st ) {
                    // cmd accepted
                    return 2;
                }else{
                    // this is put here to handle extra chars sent by the module on a successful query
                    return 1;
                }
            }else{
                // response does not have cmd data
                return 1;
            }
        }
    }
    return 0;
}

void create_leaf_message(char *messageType, char *messageSubtype, char *data,
    char *messageBuffer, int *messageBufferLen) {
    int len;

    len = snprintf(messageBuffer, (*messageBufferLen)-1, "{\"deviceId\": \"%s\",\"message\":{\"messageType\": \"%s\", \"%sType\": \"%s\", \"data\": %s}}", device_id, messageType, messageType, messageSubtype, data);
    messageBuffer[len] = 0;
    *messageBufferLen = len;
    return;
}

int build_leaf_noop( void )
{
    strcpy( leaf_build_message_buffer, noop_buff );
    return noop_len;
}

int build_leaf_message(int message_type, char *message_sub_type, char *data)
{
    char *message_type_str;
    int leaf_message_buffer_len;
    //int ticks;

    //ticks = pdMS_TO_TICKS(100);

    if (message_type == LEAF_STATISTIC) {
        message_type_str = "statistic";
    } else if (message_type == LEAF_EVENT) {
        message_type_str = "event";
    } else {
        message_type_str = "unknown";
    }

    leaf_message_buffer_len = sizeof(leaf_build_message_buffer) - 1;
    create_leaf_message(message_type_str, message_sub_type, data, leaf_build_message_buffer, &leaf_message_buffer_len);

    return leaf_message_buffer_len;

    //xMessageBufferSend(leaf_message_queue, leaf_build_message_buffer, leaf_message_buffer_len, ticks);
}

int start_leaf( struct modem_at_context *context, unsigned char cntx_id,
                                                  char *leaf_device_id, 
                                                  char *leaf_host, 
                                                  char *realm, 
                                                  char *user, 
                                                  char *password )
{
    int ret;

    strcpy(device_id, leaf_device_id);
    ret = set_leaf_host(context, leaf_host, cntx_id );
    if ( ret == MOD_AT_ST_SUCCESS ) {
        set_leaf_auth(realm, user, password);
        set_leaf_noop( );
        ret = 1;
    }else{
        ret = 0;
    }
    //init_leaf();
	return ret;
}

