#include "tencent_cos.h"
#include "dll_interface.h"
#include "cos_api.h"
#include "cos_http_io.h"
#include "cos_log.h"
extern "C" {
#ifdef _WIN32
    DLL_EXPORT
#endif
        int fastweb_module_regist(void* sol2, void* lua)
    {
        sol::state* state = static_cast<sol::state*>(sol2);
        module::tencent_cos::regist(state);
        return 0;
    }
}

module::tencent_cos::tencent_cos()
{
    if (cos_http_io_initialize(NULL, 0) != COSE_OK) {
        printf("COS HTTP INIT FAILED");
    }
}

module::tencent_cos::~tencent_cos()
{
    cos_http_io_deinitialize();
}

std::string module::tencent_cos::upfile(const std::string& appid,const std::string& endpoint,const std::string& access_key_id,const std::string& access_key_secret,const std::string& bucket_name,const std::string& object_name,const std::string& filepath)
{

    int enable_checkpoint = COS_FALSE; // 是否开启断点续传
    cos_pool_t* p = NULL;
    cos_string_t bucket;
    cos_string_t object;
    cos_string_t filename;
    cos_status_t* s = NULL;
    cos_table_t* headers = NULL;
    cos_table_t* resp_headers = NULL;
    cos_request_options_t* options = NULL;
    cos_resumable_clt_params_t* clt_params;
    cos_pool_create(&p, NULL);


    
    options = cos_request_options_create(p);

    options->config = cos_config_create(options->pool);

    cos_str_set(&options->config->endpoint, endpoint.c_str());
    cos_str_set(&options->config->access_key_id, access_key_id.c_str());
    cos_str_set(&options->config->access_key_secret, access_key_secret.c_str());
    cos_str_set(&options->config->appid, appid.c_str());
    // cos_str_set(&config->sts_token, token);  // 使用临时密钥时的 token
    options->config->is_cname = COS_FALSE;  // 是否使用自定义域名


    options->ctl = cos_http_controller_create(options->pool, 0);


    headers = cos_table_make(p, 0);
    cos_str_set(&bucket, bucket_name.c_str());
    cos_str_set(&object, object_name.c_str());
    cos_str_set(&filename, filepath.c_str());
    // upload
    clt_params = cos_create_resumable_clt_params_content(p, 1024 * 1024 * 5, 8, enable_checkpoint, NULL);
    s = cos_resumable_upload_file(options, &bucket, &object, &filename, headers, NULL,
                                  clt_params, NULL, &resp_headers, NULL);
    
    std::string result = "";
    if (cos_status_is_ok(s)) {
        result = "";
    }
    else
    {
        result = "code:" + std::to_string(s->code)+", error_code:"+s->error_code+", error_msg:"+s->error_msg;
    }
    cos_pool_destroy(p);
    return result;
}

void module::tencent_cos::regist(sol::state* lua)
{
    lua->new_usertype<module::tencent_cos>("fw_tencent_cos",
        "new", sol::constructors<module::tencent_cos()>(),
        "upfile", &module::tencent_cos::upfile
    );
}

void module::tencent_cos::regist_global(const char* name, sol::state* lua)
{
    lua->registry()[name] = this;
    (*lua)[name] = this;
}
