/* Copyright (c) 2019, NVIDIA CORPORATION.  All rights reserved. All
 * information contained herein is proprietary and confidential to NVIDIA
 * Corporation.  Any use, reproduction, or disclosure without the written
 * permission of NVIDIA Corporation is prohibited.
 */

/* Standard headers */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

/* Nvidia headers */
#include "cmdline.h"
#include "log_utils.h"
#include "misc_utils.h"
#include "config_parser.h"

/* see cmdline.h for details */
void PrintUsage()
{
    LOG_MSG("nvmimg_2d is NvMedia blit2D test program\n");
    LOG_MSG("Usage: nvmimg_2d [options]\n");
    LOG_MSG("Options:\n");
    LOG_MSG("-h           Prints usage\n");
    LOG_MSG("-v  [level]  Verbosity Level = 0(Err), 1(Warn), 2(Info), 3(Debug)\n");
    LOG_MSG("-cf [config] 2d config file. Path length limited to %u chars\n", FILE_NAME_SIZE);
}

SectionMap sectionsMap[] = {
    {SECTION_NONE, "", 0, 0} /* Has to be the last item - specifies the end of array */
};

/* see cmdline.h for details */
int ParseArgs(int argc, char *argv[], TestArgs *args)
{
    NvMediaBool bLastArg = NVMEDIA_FALSE;
    NvMediaBool bDataAvailable = NVMEDIA_FALSE;
    NvMediaStatus status = NVMEDIA_STATUS_OK;
    char *filename = NULL;
    int i;

    if (argc < 2) {
        LOG_ERR("ParseArgs: Enter proper arguments\n");
        return -1;
    }

    args->srcSurfAllocAttrs[0].type = args->dstSurfAllocAttrs[0].type = NVM_SURF_ATTR_WIDTH;
    args->srcSurfAllocAttrs[1].type = args->dstSurfAllocAttrs[1].type = NVM_SURF_ATTR_HEIGHT;
    args->srcSurfAllocAttrs[2].type = args->dstSurfAllocAttrs[2].type = NVM_SURF_ATTR_EMB_LINES_TOP;
    args->srcSurfAllocAttrs[3].type = args->dstSurfAllocAttrs[3].type = NVM_SURF_ATTR_EMB_LINES_BOTTOM;
    args->srcSurfAllocAttrs[4].type = args->dstSurfAllocAttrs[4].type = NVM_SURF_ATTR_CPU_ACCESS;
    args->srcSurfAllocAttrs[5].type = args->dstSurfAllocAttrs[5].type = NVM_SURF_ATTR_ALLOC_TYPE;
    args->srcSurfAllocAttrs[6].type = args->dstSurfAllocAttrs[6].type = NVM_SURF_ATTR_SCAN_TYPE;
    args->srcSurfAllocAttrs[7].type = args->dstSurfAllocAttrs[7].type = NVM_SURF_ATTR_COLOR_STD_TYPE;
    args->numSurfAllocAttrs = 8;

    args->srcSurfFormatAttrs[0].type = args->dstSurfFormatAttrs[0].type = NVM_SURF_ATTR_SURF_TYPE;
    args->srcSurfFormatAttrs[1].type = args->dstSurfFormatAttrs[1].type = NVM_SURF_ATTR_LAYOUT;
    args->srcSurfFormatAttrs[2].type = args->dstSurfFormatAttrs[2].type = NVM_SURF_ATTR_DATA_TYPE;
    args->srcSurfFormatAttrs[3].type = args->dstSurfFormatAttrs[3].type = NVM_SURF_ATTR_MEMORY;
    args->srcSurfFormatAttrs[4].type = args->dstSurfFormatAttrs[4].type = NVM_SURF_ATTR_SUB_SAMPLING_TYPE;
    args->srcSurfFormatAttrs[5].type = args->dstSurfFormatAttrs[5].type = NVM_SURF_ATTR_BITS_PER_COMPONENT;
    args->srcSurfFormatAttrs[6].type = args->dstSurfFormatAttrs[6].type = NVM_SURF_ATTR_COMPONENT_ORDER;

    /* ConfigParamsMap
     * See nvmedia_2d.h and sample config file(s) for details.
     */
    ConfigParamsMap paramsMap[] = {
        /*ParamName,             &args->variableName,                                paramType,     D, LimitType,   Mn, Mx, CharSize,       p2C, section   */
        {"transformMode",        &args->blitParams.dstTransform,                     TYPE_UINT,     0, LIMITS_BOTH,  0,  7,  0,              0, SECTION_NONE},
        {"filterMode",           &args->blitParams.filter,                           TYPE_UINT,     1, LIMITS_BOTH,  1,  4,  0,              0, SECTION_NONE},
        {"colorStd",             &args->blitParams.colorStandard,                    TYPE_UINT,     0, LIMITS_MIN,   0,  3,  0,              0, SECTION_NONE},
        {"validOperations",      &args->blitParams.validFields,                      TYPE_UINT,     0, LIMITS_BOTH,  0,  15, 0,              0, SECTION_NONE},
        {"inputfile",            &args->inputFileName,                               TYPE_CHAR_ARR, 0, LIMITS_NONE,  0,  0,  FILE_NAME_SIZE, 0, SECTION_NONE},
        {"outputFile",           &args->outputFileName,                              TYPE_CHAR_ARR, 0, LIMITS_NONE,  0,  0,  FILE_NAME_SIZE, 0, SECTION_NONE},
        {"crcMode",              &args->crcMode,                                     TYPE_UINT,     0, LIMITS_BOTH,  0,  2,  0,              0, SECTION_NONE},
        {"CRCFile",              &args->CRCFileName,                                 TYPE_CHAR_ARR, 0, LIMITS_NONE,  0,  0,  FILE_NAME_SIZE, 0, SECTION_NONE},
        /*src surface alloc attributes*/
        {"srcWidth",             &args->srcSurfAllocAttrs[0].value,                  TYPE_UINT,     0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"srcHeight",            &args->srcSurfAllocAttrs[1].value,                  TYPE_UINT,     0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"srcCPUAccess",         &args->srcSurfAllocAttrs[4].value,                  TYPE_UINT,     1, LIMITS_BOTH,  1,  3,  0,              0, SECTION_NONE},
        {"srcAllocType",         &args->srcSurfAllocAttrs[5].value,                  TYPE_UINT,     0, LIMITS_BOTH,  0,  1,  0,              0, SECTION_NONE},
        {"srcScanType",          &args->srcSurfAllocAttrs[6].value,                  TYPE_UINT,     1, LIMITS_BOTH,  1,  1,  0,              0, SECTION_NONE},
        {"srcColorStd",          &args->srcSurfAllocAttrs[7].value,                  TYPE_UINT,     1, LIMITS_BOTH,  1,  12, 0,              0, SECTION_NONE},
        /*src surface format attributes*/
        {"srcSurfType",          &args->srcSurfFormatAttrs[0].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  3,  0,              0, SECTION_NONE},
        {"srcLayout",            &args->srcSurfFormatAttrs[1].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  2,  0,              0, SECTION_NONE},
        {"srcDataType",          &args->srcSurfFormatAttrs[2].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  4,  0,              0, SECTION_NONE},
        {"srcMemory",            &args->srcSurfFormatAttrs[3].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  3,  0,              0, SECTION_NONE},
        {"srcSubSamplingType",   &args->srcSurfFormatAttrs[4].value,                 TYPE_UINT,     1, LIMITS_BOTH,  0,  4,  0,              0, SECTION_NONE},
        {"srcBitsPerComponent",  &args->srcSurfFormatAttrs[5].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  10, 0,              0, SECTION_NONE},
        {"srcComponentOrder",    &args->srcSurfFormatAttrs[6].value,                 TYPE_UINT,     2, LIMITS_BOTH,  1,  45, 0,              0, SECTION_NONE},
        /*srcRect*/
        {"srcRectx0",            &args->srcRect.x0,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"srcRecty0",            &args->srcRect.y0,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"srcRectx1",            &args->srcRect.x1,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"srcRecty1",            &args->srcRect.y1,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        /*dst surface alloc attributes*/
        {"dstWidth",             &args->dstSurfAllocAttrs[0].value,                  TYPE_UINT,     0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"dstHeight",            &args->dstSurfAllocAttrs[1].value,                  TYPE_UINT,     0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"dstCPUAccess",         &args->dstSurfAllocAttrs[4].value,                  TYPE_UINT,     1, LIMITS_BOTH,  1,  3,  0,              0, SECTION_NONE},
        {"dstAllocType",         &args->dstSurfAllocAttrs[5].value,                  TYPE_UINT,     0, LIMITS_BOTH,  0,  1,  0,              0, SECTION_NONE},
        {"dstScanType",          &args->dstSurfAllocAttrs[6].value,                  TYPE_UINT,     1, LIMITS_BOTH,  1,  1,  0,              0, SECTION_NONE},
        {"dstColorStd",          &args->dstSurfAllocAttrs[7].value,                  TYPE_UINT,     1, LIMITS_BOTH,  1,  12, 0,              0, SECTION_NONE},
        /*dst surface format attributes*/
        {"dstSurfType",          &args->dstSurfFormatAttrs[0].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  3,  0,              0, SECTION_NONE},
        {"dstLayout",            &args->dstSurfFormatAttrs[1].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  2,  0,              0, SECTION_NONE},
        {"dstDataType",          &args->dstSurfFormatAttrs[2].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  4,  0,              0, SECTION_NONE},
        {"dstMemory",            &args->dstSurfFormatAttrs[3].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  3,  0,              0, SECTION_NONE},
        {"dstSubSamplingType",   &args->dstSurfFormatAttrs[4].value,                 TYPE_UINT,     1, LIMITS_BOTH,  0,  4,  0,              0, SECTION_NONE},
        {"dstBitsPerComponent",  &args->dstSurfFormatAttrs[5].value,                 TYPE_UINT,     1, LIMITS_BOTH,  1,  10, 0,              0, SECTION_NONE},
        {"dstComponentOrder",    &args->dstSurfFormatAttrs[6].value,                 TYPE_UINT,     2, LIMITS_BOTH,  1,  45, 0,              0, SECTION_NONE},
        /*dstRect*/
        {"dstRectx0",            &args->dstRect.x0,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"dstRecty0",            &args->dstRect.y0,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"dstRectx1",            &args->dstRect.x1,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        {"dstRecty1",            &args->dstRect.y1,                                  TYPE_USHORT,   0, LIMITS_MIN,   0,  0,  0,              0, SECTION_NONE},
        /*End of the array */
        {NULL,                   NULL,                                               TYPE_UINT,     0, LIMITS_NONE,  0,  0, 0,               0, SECTION_NONE}
    };

    for (i = 1; i < argc; i++) {
        /* check if this is the last argument*/
        bLastArg = ((argc - i) == 1);

        /* check if there is data available to be parsed following the option*/
        bDataAvailable = (!bLastArg) && !(argv[i+1][0] == '-');

        if (argv[i][0] == '-') {
            if (strcmp(&argv[i][1], "h") == 0) {
                return -1;
            }
            else if (strcmp(&argv[i][1], "v") == 0) {
                if (bDataAvailable) {
                    args->logLevel = atoi(argv[++i]);
                    if (args->logLevel < LEVEL_ERR || args->logLevel > LEVEL_DBG) {
                        LOG_ERR("ParseArgs: Invalid logging level chosen (%d).\n", args->logLevel);
                        LOG_ERR("           default logging level is LEVEL_ERR \n");
                        args->logLevel = LEVEL_ERR;
                    }
                }
                SetLogLevel(args->logLevel);
            }
            else if (strcmp(&argv[i][1], "cf") == 0) {
                /* Init Parser Map*/
                LOG_INFO("ParseArgs: Initializing Parser Params Map\n");
                status = ConfigParser_InitParamsMap(paramsMap);
                if (status != NVMEDIA_STATUS_OK) {
                    LOG_ERR("ERR: ConfigParser_InitParamsMap failed! status:%x\n", status);
                    return -1;
                }

                filename = argv[++i];
                if (!filename) {
                    LOG_ERR("ERR: Invalid config file name\n");
                    return -1;
                }
                LOG_INFO("ParseArgs: Parsing config file %s\n", filename);
                status = ConfigParser_ParseFile(paramsMap, 1, sectionsMap, filename);
                if (status != NVMEDIA_STATUS_OK) {
                    LOG_ERR("ERR: Failed to parse config file. status:%x\n", status);
                    return -1;
                }
            }
            else
            {
                LOG_ERR("ERR: option %c is not supported\n", argv[i][1]);
                return -1;
            }
        }
    }

    LOG_INFO("ParseArgs: Validating params from config file\n");
    status = ConfigParser_ValidateParams(paramsMap, sectionsMap);
    if (status != NVMEDIA_STATUS_OK) {
        LOG_ERR("ERR: Some of the params in config file are invalid.\n");
        return -1;
    }

    if (args->logLevel > LEVEL_ERR) {
        LOG_INFO("ParseArgs: Printing params from config file\n");
        ConfigParser_DisplayParams(paramsMap, sectionsMap);
    }

    return 0;
}

