//
//  ServerConfiguration.cpp
//  eagle0_server
//
//  Created by Dan Crosby on 1/21/18.
//  Copyright © 2018 none. All rights reserved.
//

#include "ServerConfiguration.hpp"

#include <cstring>
#include <fstream>
#include <iostream>

#include "src/main/cpp/net/eagle0/common/FilesystemUtils.hpp"

#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif
const string ServerConfiguration::kShardokGrpcAddress = "shardokGrpcAddress";
const string ServerConfiguration::kEagleInterfaceGrpcAddress = "eagleInterfaceGrpcAddress";
const string ServerConfiguration::kEagleGrpcAddress = "eagleGrpcAddress";
const string ServerConfiguration::kSslCertPath = "sslCertPath";
const string ServerConfiguration::kSslPrivateKeyPath = "sslPrivateKeyPath";
#pragma GCC diagnostic pop

using std::unordered_map;

unordered_map<string, string> DefaultValues();

unordered_map<string, string> DefaultValues() {
    return unordered_map<string, string>{
            {ServerConfiguration::kShardokGrpcAddress, "localhost"},
            {ServerConfiguration::kEagleInterfaceGrpcAddress, "localhost"}};
}

ServerConfiguration::ServerConfiguration(const string& filePath) {
    if (!FilesystemUtils::FileExistsAtPath(filePath)) {
        std::cerr << "Config file not found at " << filePath << std::endl;
        configValues = DefaultValues();
        return;
    }
    std::ifstream istr(filePath);

    char line[256];
    while (!istr.eof()) {
        istr.getline(line, 256);
        if (strnlen(line, 256) < 3) continue;
        string key = strtok(line, " =");
        string value = strtok(NULL, " =");

        configValues[key] = value;
    }
}

int ServerConfiguration::intForKey(const string& key, const int defaultValue) {
    const auto foundVal = configValues.find(key);
    if (foundVal == configValues.end()) { return defaultValue; }
    return std::stoi(foundVal->second);
}

string ServerConfiguration::stringForKey(const string& key, const string& defaultValue) {
    const auto foundVal = configValues.find(key);
    if (foundVal == configValues.end()) { return defaultValue; }
    return foundVal->second;
}
