/*
 *               Copyright (C) 2007, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */


#include <nup.h>
#include <shr_th.h>
#include <string.h>

#include "nup_cache.h"
#include "nup_init.h"
#include "nup_log.h"
#include "nup_mem.h"
#include "nup_op.h"
#include "nup_stdlib.h"


/* Need a bit over 4KB of stack size, mostly used by the IOSC library */
#define NUP_ASYNC_THREAD_STACK_SIZE (8 * 1024)

/* Context info */
typedef struct {
    _SHRThread thread;
    u8 asyncThreadStack[NUP_ASYNC_THREAD_STACK_SIZE];
    _SHRMessageQueue asyncQueue;
    _SHRMessage asyncMsg;
    NUPAsyncCmdBlock cmdBlk;
} NUPContext;

static NUPContext __nupCtx;


NUPError
NUP_Init(const NUPNameValue *args, u32 nArgs)
{
    NUPError rv = NUP_ERROR_OK;
    u32 i, logLevel = NUP_LOG_NONE, threadPrio = 0xffffffff;
    const NUPNameValue *arg;
    NUPAlloc alloc = 0;
    NUPFree free = 0;
    const char *hostname = NULL, *country = NULL, *region = NULL;
    _SHRThreadAttr thrAttr;

    if (nArgs > 0 && args == NULL) {
        NUP_LOG(NUP_LOG_ERR, "Invalid arguments\n");
        rv = NUP_ERROR_INVALID;
        goto end;
    }

    memset(&__nupCtx, 0, sizeof(__nupCtx));

    for (i = 0; i < nArgs; i++) {
        arg = &args[i];

        if (strncmp(arg->name, NUP_ALLOC, sizeof(NUP_ALLOC)) == 0
               && arg->name[sizeof(NUP_ALLOC) - 1] == 0) {
            alloc = (NUPAlloc) arg->value;
            continue;
        }

        if (strncmp(arg->name, NUP_FREE, sizeof(NUP_FREE)) == 0
               && arg->name[sizeof(NUP_FREE) - 1] == 0) {
            free = (NUPFree) arg->value;
            continue;
        }

        if (strncmp(arg->name, NUP_LOG_LEVEL, sizeof(NUP_LOG_LEVEL)) == 0
               && arg->name[sizeof(NUP_LOG_LEVEL) - 1] == 0) {
            logLevel = *(u32 *) arg->value;
            continue;
        }

        if (strncmp(arg->name, NUP_HOSTNAME, sizeof(NUP_HOSTNAME)) == 0
               && arg->name[sizeof(NUP_HOSTNAME) - 1] == 0) {
            hostname = arg->value;
            continue;
        }

        if (strncmp(arg->name, NUP_COUNTRY, sizeof(NUP_COUNTRY)) == 0
               && arg->name[sizeof(NUP_COUNTRY) - 1] == 0) {
            country = arg->value;
            continue;
        }

        if (strncmp(arg->name, NUP_REGION, sizeof(NUP_REGION)) == 0
               && arg->name[sizeof(NUP_REGION) - 1] == 0) {
            region = arg->value;
            continue;
        }

        if (strncmp(arg->name, NUP_THREAD_PRIO, sizeof(NUP_THREAD_PRIO)) == 0
               && arg->name[sizeof(NUP_THREAD_PRIO) - 1] == 0) {
            threadPrio = *(u32 *) arg->value;
            continue;
        }
    }

    rv = nupSetLogLevel(logLevel);
    if (rv != NUP_ERROR_OK) {
        goto end;
    }

    if (alloc == 0 || free == 0 || hostname == NULL || country == NULL || region == NULL || threadPrio == 0xffffffff) {
        NUP_LOG(NUP_LOG_ERR, "Invalid or missing arguments\n");
        rv = NUP_ERROR_INVALID;
        goto end;
    }

    rv = nupSetAllocator(alloc, free);
    if (rv != NUP_ERROR_OK) {
        goto end;
    }

    rv = nupSetOpParam(hostname, country, region);
    if (rv != NUP_ERROR_OK) {
        goto end;
    }

    /* Platform-specific init */
    rv = nupPlatformInit(args, nArgs);
    if (rv != NUP_ERROR_OK) {
        goto end;
    }

    rv = nupInitCache();
    if (rv != NUP_ERROR_OK) {
        goto end;
    }

    rv = _SHR_message_queue_init(&__nupCtx.asyncQueue, &__nupCtx.asyncMsg, 1);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to initialize message queue\n");
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

    /* TODO: add IOS_THREAD_CREATE_JOINABLE when porting to NetCard */
    thrAttr.stack = (void *) __nupCtx.asyncThreadStack;
    thrAttr.stackSize = sizeof(__nupCtx.asyncThreadStack);
    thrAttr.priority = threadPrio;
    thrAttr.start = 1;

    rv = _SHR_thread_create(&__nupCtx.thread, &thrAttr, (_SHRThreadFunc) nupAsyncOp, &__nupCtx.asyncQueue);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to create and start async thread\n");
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

    __nupCtx.cmdBlk.cmd = NUP_ASYNC_CMD_NONE;
    __nupCtx.cmdBlk.progress.status = NUP_ERROR_NOT_BUSY;

    rv = _SHR_mutex_init(&__nupCtx.cmdBlk.progressMux, _SHR_MUTEX_RECURSIVE, 0, 0);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to initialize mutex\n");
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

end:
    /*
     * TODO: clean up after errors. The only thing that needs to be
     * cleaned up now is the async op thread, which would involve
     * adding a new _SHR_thread_destroy() function. This fix is not
     * critical since if NUP_Init() fails, things are broken already
     * anyways
     */

    return rv;
}


NUPError
NUP_CheckAsync(u32 attr, ESTitleId *titleIds, u32 *nTitleIds)
{
    NUPError rv = NUP_ERROR_OK;

    if (nTitleIds == NULL) {
        NUP_LOG(NUP_LOG_ERR, "Invalid arguments\n");
        rv = NUP_ERROR_INVALID;
        goto end;
    }

    if (__nupCtx.cmdBlk.cmd != NUP_ASYNC_CMD_NONE) {
        NUP_LOG(NUP_LOG_ERR, "Trying to initiate check command while busy\n");
        rv = NUP_ERROR_BUSY;
        goto end;
    }

    __nupCtx.cmdBlk.cmd = NUP_ASYNC_CMD_CHECK;

    __nupCtx.cmdBlk.arg.checkArg.attr = attr;
    __nupCtx.cmdBlk.arg.checkArg.titleIds = titleIds;
    __nupCtx.cmdBlk.arg.checkArg.nTitleIds = nTitleIds;

    __nupCtx.cmdBlk.progress.status = NUP_ERROR_NOT_DONE;
    __nupCtx.cmdBlk.progress.totalBytes = 0;
    __nupCtx.cmdBlk.progress.currentBytes = 0;

    rv = _SHR_message_send(&__nupCtx.asyncQueue, (_SHRMessage) &__nupCtx.cmdBlk, _SHR_MESSAGE_NOBLOCK);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to send message to async thread, rv=%d\n", rv);
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

end:
    return rv;
}


NUPError
NUP_DownloadAsync(u32 attr, const ESTitleId *titleIds, u32 nTitleIds)
{
    NUPError rv = NUP_ERROR_OK;

    if (__nupCtx.cmdBlk.cmd != NUP_ASYNC_CMD_NONE) {
        NUP_LOG(NUP_LOG_ERR, "Trying to initiate download command while busy\n");
        rv = NUP_ERROR_BUSY;
        goto end;
    }

    __nupCtx.cmdBlk.cmd = NUP_ASYNC_CMD_DOWNLOAD;

    __nupCtx.cmdBlk.arg.downloadArg.attr = attr;
    __nupCtx.cmdBlk.arg.downloadArg.titleIds = titleIds;
    __nupCtx.cmdBlk.arg.downloadArg.nTitleIds = nTitleIds;

    __nupCtx.cmdBlk.progress.status = NUP_ERROR_NOT_DONE;
    __nupCtx.cmdBlk.progress.totalBytes = 0;
    __nupCtx.cmdBlk.progress.currentBytes = 0;

    rv = _SHR_message_send(&__nupCtx.asyncQueue, (_SHRMessage) &__nupCtx.cmdBlk, _SHR_MESSAGE_NOBLOCK);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to send message to async thread, rv=%d\n", rv);
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

end:
    return rv;
}


NUPError
NUP_GetProgress(NUPProgress *progress)
{
    NUPError rv = NUP_ERROR_OK;

    if (progress == NULL) {
        NUP_LOG(NUP_LOG_ERR, "Invalid arguments\n");
        rv = NUP_ERROR_INVALID;
        goto end;
    }

    _SHR_mutex_lock(&__nupCtx.cmdBlk.progressMux);
    memcpy(progress, &__nupCtx.cmdBlk.progress, sizeof(*progress));
    _SHR_mutex_unlock(&__nupCtx.cmdBlk.progressMux);

end:
    return rv;
}


NUPError
NUP_CleanUp(void)
{
    NUPError rv = NUP_ERROR_OK;

    if (__nupCtx.cmdBlk.cmd != NUP_ASYNC_CMD_NONE) {
        NUP_LOG(NUP_LOG_ERR, "Can not shut down NUP when there's an outstanding operation\n");
        rv = NUP_ERROR_BUSY;
        goto end;
    }

    __nupCtx.cmdBlk.cmd = NUP_ASYNC_CMD_SHUTDOWN;
    rv = _SHR_message_send(&__nupCtx.asyncQueue, (_SHRMessage) &__nupCtx.cmdBlk, _SHR_MESSAGE_NOBLOCK);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to send message to async thread, rv=%d\n", rv);
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

    rv = _SHR_thread_join(&__nupCtx.thread, NULL, 0);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to join async thread, rv=%d\n");
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

    rv = _SHR_mutex_destroy(&__nupCtx.cmdBlk.progressMux);
    if (rv != _SHR_ERR_OK) {
        NUP_LOG(NUP_LOG_ERR, "Failed to destroy progress mutex, rv=%d\n");
        rv = NUP_ERROR_INTERNAL;
        goto end;
    }

    /*
     * TODO: add message queue destroy. This would involve adding a
     * new _SHR_message_queue_destroy() function. This fix is not
     * critical for TWL since it's a no-op on TWL anyways
     */ 

    rv = nupCleanUpCache();
    if (rv != NUP_ERROR_OK) {
        goto end;
    }

    /* Platform-specific clean-up */
    rv = nupPlatformCleanUp();
    if (rv != NUP_ERROR_OK) {
        goto end;
    }

end:
    return rv;
}
