#include "client.h"
#include "version.h"
#include <SimpleIni.h>
#include <filesystem>
#include <iostream>
#include <of_path.h>

using namespace ofen;
namespace fs = std::filesystem;

struct TransmSet {
    std::string ip{};
    std::string port{};
};

std::shared_ptr<spdlog::logger> g_Logger = nullptr;
bool gen_default_ini(const std::string& path)
{
    g_Logger->warn("Gen Default Setting Ini in [{}].", path);
    CSimpleIniA ini_handle{};
    ini_handle.LoadFile(path.c_str());
    ini_handle.SetValue("Setting", "IP", "127.0.0.1");
    ini_handle.SetValue("Setting", "PORT", "8989");
    ini_handle.SaveFile(path.c_str());
    return true;
}

bool read_ini(TransmSet& set)
{
    fs::path home(COfPath::get_home());
    std::string config_path = home.append("transm.ini").string();
    if (!fs::exists(config_path) && !gen_default_ini(config_path)) {
        return false;
    }
    CSimpleIniA ini_handle{};
    SI_Error ret = ini_handle.LoadFile(config_path.c_str());
    if (ret != SI_OK) {
        g_Logger->error("Load Ini [{}] Failed.", config_path);
        return false;
    }
    set.ip = ini_handle.GetValue("Setting", "IP");
    set.port = ini_handle.GetValue("Setting", "PORT");
    return true;
}

int main(int argc, char* argv[])
{
    auto log_path = ofen::COfPath::to_full("client.log");
    g_Logger = get_logger("client", log_path);
    g_Logger->info("Configure At {} under {} on {}", VERSION_BUILD_DATE, VERSION_GIT_HASH,
                   VERSION_GIT_BRANCH);
    TransmSet set;
    if (!read_ini(set)) {
        return -1;
    }
    CClient client(g_Logger);
    client.run(set.ip, set.port);
    g_Logger->info("exit &&&&&&&&&&&&&");
    return 0;
}