#include <stdarg.h>

#include "tc_private/tc_handle.h"
#include "tc_private/tc_private.h"

#include "log/log.h"

#include "tc_tpm2.h"
#include "tpm2_common.h"

#include "tc_type.h"
#include "tc_errcode.h"

struct tpm2_load_ctx
{
    TC_HANDLE        handle;
    uint32_t         key_index;
    TC_BUFFER       *parent_auth_msg;
};

TC_RC tpm2_load_init(struct api_ctx_st *api_ctx, int num, ...)
{
    TC_RC rc = TC_SUCCESS;
    struct tpm2_load_ctx* lctx = (struct tpm2_load_ctx*)malloc(sizeof(struct tpm2_load_ctx));

    va_list ap;
    va_start(ap, num);
    lctx->handle = va_arg(ap, TC_HANDLE);
    lctx->key_index = va_arg(ap, uint32_t);
    lctx->parent_auth_msg = va_arg(ap, TC_BUFFER*);
    va_end(ap);

    api_ctx->data = (HANDLE_DATA*)lctx;
    return  rc;
}

TC_RC tpm2_load_free(struct api_ctx_st *api_ctx)
{
    TC_RC rc = TC_SUCCESS;  
    free(api_ctx->data); 
    api_ctx->data = NULL;
    api_ctx->cmd_code = API_NULL;
    return rc;
}

TC_RC tpm2_load(API_CTX *ctx)
{
    TC_RC rc = TC_SUCCESS;

    struct tpm2_load_ctx* lctx = (struct tpm2_load_ctx*)ctx->data;
    TC_HANDLE_CTX* tc_handle_ctx = (TC_HANDLE_CTX*)(lctx->handle);

    TSS2L_SYS_AUTH_RESPONSE sessionsDataOut;
    TSS2L_SYS_AUTH_COMMAND sessionsData = {
        .auths    = {{.sessionHandle = TPM2_RS_PW}},
        .count    = 1
    };

    if (lctx->key_index > tc_handle_ctx->handle.tc_object->count) {
        log_error("Invalid object index\n");
        return TC_OBJECT_INDEX;
    }

    if (lctx->parent_auth_msg != NULL) {
        if (lctx->parent_auth_msg->size > sizeof(TPMU_HA)) {
            log_error("The authorized authentication password of the parent key exceeds the length limit\n");
            return TC_AUTH_HMAC_OVERSIZE;
        }
        sessionsData.auths[0].hmac.size = lctx->parent_auth_msg->size;
        memcpy(sessionsData.auths[0].hmac.buffer,
               lctx->parent_auth_msg->buffer,
               lctx->parent_auth_msg->size);
    }

    TPM2B_NAME* name = (TPM2B_NAME*)tc_handle_ctx->handle.tc_object->node_info[lctx->key_index]->obj_name;
    name->size = BUFFER_SIZE(TPM2B_NAME, name);


    rc = Tss2_Sys_Load((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                        tc_handle_ctx->handle.tc_object->node_info[lctx->key_index]->parent_handle,
                        &sessionsData,
                        (TPM2B_PRIVATE*)tc_handle_ctx->handle.tc_object->node_info[lctx->key_index]->obj_private,
                        (TPM2B_PUBLIC*)tc_handle_ctx->handle.tc_object->node_info[lctx->key_index]->obj_public,
                        &tc_handle_ctx->handle.tc_object->node_info[lctx->key_index]->obj_handle,
                        name,
                        &sessionsDataOut);

    if (rc != TSS2_RC_SUCCESS) {
        log_error("Failed to run api_load:0x%0x\n", rc);
        rc = TC_COMMAND_LOAD;
    }
    return rc;
}