#include <sys/timeb.h>
#include <string.h>
#include <model_code.h>
#include <algorithm>
#include "system_utils.h"
#include "crypto/basic.h"
#include "crypto/sha256_utils.h"
#include "io_utils.h"
#include "log.h"
#include "../constant/constant_model.h"

const char alphabet[] = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(){}[]<>?~";

namespace util {

int SystemUtils::intN(int n) {
    return rand() % n;
}

std::string SystemUtils::random_key_iv(int len) {
    unsigned char* tmp = (unsigned char*) malloc(sizeof(unsigned char) * len);
    int ret = util::crypto::Basic::random(tmp, len);
    std::string tmp_str(reinterpret_cast<const char*>(tmp), len);
    free(tmp);
    return tmp_str;
}

std::string SystemUtils::random_str(int len) {
    unsigned char* tmp = (unsigned char*) malloc(sizeof(unsigned char) * len);
    int ret = util::crypto::Basic::random(tmp, len);
    std::string tmp_str(reinterpret_cast<const char*>(tmp), len);
    free(tmp);
    return tmp_str;
}

int SystemUtils::check_key_match(const char* key, const char* filepath) {
    std::string aes_key_iv(key, key + constant::CONSTANT_AES_GCM_KEY_LEN);
    std::string sha256_aes_key_iv = util::crypto::SHA256Utils::sha256_string(aes_key_iv);

    unsigned char* data_pos = (unsigned char*) malloc(sizeof(unsigned char) * 64);
    int ret =
        ioutil::read_with_pos_and_length(filepath, data_pos, constant::MAGIC_NUMBER_LEN + constant::VERSION_LEN, 64);
    if (ret != CODE_OK) {
	free(data_pos);
        LOGD("[M]read file failed when check key");
        return ret;
    }
    std::string check_str((char*) data_pos, 64);
    free(data_pos);

    if (strncmp(sha256_aes_key_iv.c_str(), check_str.c_str(), 64) != 0) {
        return CODE_KEY_NOT_MATCH;
    }
    return CODE_OK;
}

/**
 *
 * @param filepath
 * @return 0 - file encrypted    1 - file unencrypted
 */
int SystemUtils::check_file_encrypted(const char* filepath) {
    size_t read_len = constant::MAGIC_NUMBER_LEN + constant::VERSION_LEN;
    unsigned char* data_pos = (unsigned char*) malloc(sizeof(unsigned char) * read_len);
    if (ioutil::read_with_pos_and_length(filepath, data_pos, 0, read_len) != CODE_OK) {
	free(data_pos);
        LOGD("check file failed when read %s(file)", filepath);
        return CODE_OPEN_FAILED;
    }

    std::string tag(constant::MAGIC_NUMBER);
    tag.append(constant::VERSION);
    int ret_cmp = strncmp(tag.c_str(), (const char*) data_pos, read_len) == 0 ? 0 : 1;
    free(data_pos);
    return ret_cmp;
}

int SystemUtils::check_pattern_exist(const std::vector<std::string>& vecs, const std::string& pattern) {

    if (std::find(vecs.begin(), vecs.end(), pattern) == vecs.end()) {
        return -1; // not exist
    } else {
        return 0; // exist
    }
}

}
