#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_encrypt_ctx
{
    TC_HANDLE        handle;
    uint32_t         key_index;
    TC_BUFFER       *key_auth_msg;
    TC_ALG           alg_encrypt;
    TC_BUFFER       *plain_text;
    TC_BUFFER       *ciphter_text;
};

TC_RC tpm2_encrypt_init(struct api_ctx_st *api_ctx, int num, ...)
{
    TC_RC rc = TC_SUCCESS;
    struct tpm2_encrypt_ctx* ectx = (struct tpm2_encrypt_ctx*)malloc(sizeof(struct tpm2_encrypt_ctx));

    va_list ap;
    va_start(ap, num);
    ectx->handle = va_arg(ap, TC_HANDLE);
    ectx->key_index = va_arg(ap, uint32_t);
    ectx->key_auth_msg = va_arg(ap, TC_BUFFER*);
    ectx->alg_encrypt = va_arg(ap, TC_ALG);
    ectx->plain_text = va_arg(ap, TC_BUFFER*);
    ectx->ciphter_text = va_arg(ap, TC_BUFFER*);
    va_end(ap);

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

TC_RC tpm2_encrypt_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_encrypt(API_CTX *ctx)
{
    TC_RC rc = TC_SUCCESS;

    struct tpm2_encrypt_ctx* ectx = (struct tpm2_encrypt_ctx*)ctx->data;
    TC_HANDLE_CTX* tc_handle_ctx = (TC_HANDLE_CTX*)(ectx->handle);

    if (ectx->alg_encrypt == TC_RSA) {
        TPMT_RSA_DECRYPT scheme;
        TPM2B_DATA label;
        TPM2B_PUBLIC_KEY_RSA out_data = TPM2B_TYPE_INIT(TPM2B_PUBLIC_KEY_RSA, buffer);
        TPM2B_PUBLIC_KEY_RSA in_data =TPM2B_TYPE_INIT(TPM2B_PUBLIC_KEY_RSA, buffer);
        TSS2L_SYS_AUTH_RESPONSE sessionsDataout;
        scheme.scheme = TPM2_ALG_RSAES;
        label.size = 0;
        if (ectx->plain_text->size > TPM2_MAX_RSA_KEY_BYTES) {
            log_error("The length of the data to be encrypted exceeds the limit\n");
            return TC_ENCRYPT_BUFFER_OVERSIZE;
        }
        in_data.size = ectx->plain_text->size;
        memcpy (in_data.buffer,
                ectx->plain_text->buffer,
                ectx->plain_text->size);

        if (ectx->key_index > MAX_OBJECT_NODE_COUNT) {
            rc = Tss2_Sys_RSA_Encrypt((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                       ectx->key_index,
                                       NULL,
                                       &in_data,
                                       &scheme,
                                       &label,
                                       &out_data,
                                       &sessionsDataout);
        }else{
            if (ectx->key_index > tc_handle_ctx->handle.tc_object->count) {
                log_error("Invalid object index\n");
                return TC_OBJECT_INDEX;
            }
            rc = Tss2_Sys_RSA_Encrypt((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                       tc_handle_ctx->handle.tc_object->node_info[ectx->key_index]->obj_handle,
                                       NULL,
                                       &in_data,
                                       &scheme,
                                       &label,
                                       &out_data,
                                       &sessionsDataout);
        }
        ectx->ciphter_text->buffer = (uint8_t*)malloc(out_data.size);
        memcpy(ectx->ciphter_text->buffer, out_data.buffer, out_data.size);
        ectx->ciphter_text->size = out_data.size; 
    }else{
        TPM2B_MAX_BUFFER out_data = TPM2B_TYPE_INIT(TPM2B_MAX_BUFFER, buffer);
        TPM2B_MAX_BUFFER in_data = TPM2B_TYPE_INIT(TPM2B_MAX_BUFFER, buffer);
        TPM2B_IV iv_out = TPM2B_TYPE_INIT(TPM2B_IV, buffer);
        TSS2L_SYS_AUTH_RESPONSE sessionsDataout;
        TSS2L_SYS_AUTH_COMMAND sessionsData = {
            .auths    = {{.sessionHandle = TPM2_RS_PW}},
            .count    = 1
        };
        TPM2B_IV iv_in = {
            .size = TPM2_MAX_SYM_BLOCK_SIZE,
            .buffer = { 0 }
        };
        if (ectx->plain_text->size > TPM2_MAX_DIGEST_BUFFER) {
            log_error("The length of the data to be encrypted exceeds the limit\n");
            return TC_ENCRYPT_BUFFER_OVERSIZE;
        }
        in_data.size = ectx->plain_text->size;
        memcpy (in_data.buffer,
                ectx->plain_text->buffer,
                ectx->plain_text->size);

        if (ectx->key_auth_msg != NULL) {
            if (ectx->key_auth_msg->size > sizeof(TPMU_HA)) {
                log_error("Key authorization authentication password exceeds limit\n");
                return TC_AUTH_HMAC_OVERSIZE;
            }
            sessionsData.auths[0].hmac.size = ectx->key_auth_msg->size;
            memcpy(sessionsData.auths[0].hmac.buffer,
                   ectx->key_auth_msg->buffer,
                   ectx->key_auth_msg->size);
        }

        if (ectx->key_index > MAX_OBJECT_NODE_COUNT) {
            rc = Tss2_Sys_EncryptDecrypt((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                          ectx->key_index,
                                          &sessionsData,
                                          TPM2_NO,
                                          TPM2_ALG_NULL,
                                          &iv_in,
                                          &in_data,
                                          &out_data,
                                          &iv_out,
                                          &sessionsDataout);
        }else{
            if (ectx->key_index > tc_handle_ctx->handle.tc_object->count) {
                log_error("Invalid object index\n");
                return TC_OBJECT_INDEX;
            }
            rc = Tss2_Sys_EncryptDecrypt2((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                        tc_handle_ctx->handle.tc_object->node_info[ectx->key_index]->obj_handle,
                                        &sessionsData,
                                        &in_data,
                                        TPM2_NO,
                                        TPM2_ALG_NULL,
                                        &iv_in,
                                        &out_data,
                                        &iv_out,
                                        &sessionsDataout);
            if (rc != TSS2_RC_SUCCESS) {
                rc = Tss2_Sys_EncryptDecrypt((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                          tc_handle_ctx->handle.tc_object->node_info[ectx->key_index]->obj_handle,
                                          &sessionsData,
                                          TPM2_NO,
                                          TPM2_ALG_NULL,
                                          &iv_in,
                                          &in_data,
                                          &out_data,
                                          &iv_out,
                                          &sessionsDataout);
            }
        }
        ectx->ciphter_text->buffer = (uint8_t*)malloc(out_data.size);
        memcpy(ectx->ciphter_text->buffer, out_data.buffer, out_data.size);
        ectx->ciphter_text->size = out_data.size;
    }

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