/*
 * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL). See the LICENSE file in the root
 * directory for license terms. You may choose either license, or both.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "iotcs_port_persistence.h"
#include "util/util_memory.h"
#include "iotcs_port_system.h"
#include "util/util.h"

#include "log/log.h"
#define IOTCSP_MODULE_LOG_CHANNEL IOTCS_LOG_CHANNEL_LOG
#include "log/log_template.h"

extern char* g_tam_path_prefix;

static const char *fixup_path(char* path) {
    if (strncmp(g_tam_path_prefix, path, strlen(g_tam_path_prefix)) == 0) {
        return util_safe_strcpy(path);
    }
    if (strncmp("./", path, 2) == 0) {
        path += 2;
    }
    size_t len = strlen(path) + strlen(g_tam_path_prefix) + 1;
    char *newpath = (char*) util_malloc(len);
    if (newpath != NULL) {
        if (0 > util_safe_snprintf(newpath, len, "%s%s", g_tam_path_prefix, path)) {
            util_free(newpath);
            return NULL;
        }
    }
    return newpath;
}

iotcs_result load_from_file(char *file_name, char **buffer, iotcs_bool silent) {
    const char *fixed_name = fixup_path(file_name);
    FILE *file = fopen(fixed_name, "r");
    if (!file) {
        if (!silent) {
            LOG_WARN("Can not open file \"%s\"", fixed_name);
        }
        return IOTCS_RESULT_FAIL;
    }
    fseek(file, 0, SEEK_END);
    long fsize = ftell(file);
    fseek(file, 0, SEEK_SET);

    *buffer = (char*)util_malloc((fsize + 1) * sizeof(char));
    fread(*buffer, fsize, 1, file);
    fclose(file);

    (*buffer)[fsize] = 0;
    return IOTCS_RESULT_OK;
}
void remove_file(char *file_name) {
    const char *fixed_name = fixup_path(file_name);
    remove(fixed_name);
}

void save_to_file(char *file_name, const char *buffer) {
    const char *fixed_name = fixup_path(file_name);
    FILE *file = fopen(fixed_name, "w");
    if (!file) {
        LOG_WARN("Can not open file \"%s\"", fixed_name);
        return;
    }
    if (fwrite(buffer, sizeof(char), strlen(buffer), file) != strlen(buffer) * sizeof(char)) {
        LOG_WARN("Can not write to the file \"%s\"", fixed_name);
    }
    fclose(file);
}