/*
 * Copyright (c) 2017, 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"

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

    *buffer = 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) {
    remove(file_name);
}

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