#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include <filesystem>
#include <map>
#include <time.h>
#include <C:\Users\sriff\Downloads\Practicum_Stuff\SoftwareEngineeringTeam2Proj\ArduinoServerTest\include\asio-1.28.0\include\asio.hpp>
// #include <pqxx/pqxx> // <-- TODO: The library header isnt exactly a header and I'm stuck on how to approach getting it to include correctly

using namespace std;
using namespace asio;
using namespace asio::ip;
namespace fs = std::filesystem;

// Config file just for the port used? Too little I will pass for now
int portVal = 999;

// Global map to store open file streams for each MAC address
map<string, ofstream> macFiles;

/*
void setupDatabase() {
    try {
        // Establish a connection to the PostgreSQL database
        pqxx::connection conn("dbname=database user=postgres password=password hostaddr=127.0.0.1 port=5432");
        if (conn.is_open()) {
            cout << "Opened database successfully: " << conn.dbname() << endl;
        }
        else {
            cerr << "Failed to open database" << endl;
            return;
        }

        // Start a transaction
        pqxx::dbtransaction txn(conn);

        // Create a new table
        txn.exec("CREATE TABLE IF NOT EXISTS sensorTable ("
            "time VARCHAR(14),"
            "mac VARCHAR(17),"
            "sensorvalue VARCHAR(255)"
            ");");

        // Commit the transaction
        txn.commit();

        cout << "Database setup completed successfully" << endl;

        // Close the connection
        conn.close();
    }
    catch (const exception& e) {
        cerr << e.what() << endl;
    }
}
*/

/*
 // Function to send sensor data to postgresql database
void saveToDatabase(const string& pkg) {
    try {
        // Establish a connection to the PostgreSQL database
        pqxx::connection conn("dbname=database user=postgres password=password hostaddr=127.0.0.1 port=5432");

        if (conn.is_open()) {
            cout << "Opened database successfully: " << conn.dbname() << endl;
        }
        else {
            cerr << "Failed to open database" << endl;
            return;
        }

        // Create a transaction
        pqxx::work txn(conn);

        // Prepare the query string
        std::stringstream query;
        query << "INSERT INTO sensorTable (time, mac, sensorvalue) VALUES ("
            << pkg.substr(0, 14) << ", '"  // Assuming time is the first 14 characters
            << pkg.substr(15, 17) << "', " // Assuming mac address is from character 15 to 31
            << pkg.substr(33) << ")";      // Assuming sensor value is after the mac address

        // Execute the query
        txn.exec(query.str());

        // Commit the transaction
        txn.commit();

        cout << "Records inserted successfully" << endl;

        // Close the connection
        conn.close();
    }
    catch (const exception& e) {
        cerr << e.what() << endl;
    }
}
*/

// Function to write sensor data to log files
void writeToLog(const string& macAddress, const string& data) {
    // Check if a /log directory exists
    fs::path logDir = fs::path(fs::current_path()) / "log";
    if (!fs::exists(logDir) || !fs::is_directory(logDir)) {
        fs::create_directory(logDir);
    }

    // Filesystem cannot create a new file with ':' in the filename
    string macAddressStripped = macAddress;
    macAddressStripped.erase(remove(macAddressStripped.begin(), macAddressStripped.end(), ':'), macAddressStripped.end());

    // Check if a file for the MAC address exists
    fs::path filePath = logDir / (macAddressStripped + ".csv");
    if (!fs::exists(filePath)) {
        // Create a new file for the MAC address
        ofstream newFile(filePath);
        if (newFile.is_open()) {
            newFile << data << endl;
            newFile.close();
        }
    }
    // Existing MAC address, append to the existing file
    else {
        ofstream existingFile(filePath, ios_base::app);
        if (existingFile.is_open()) {
            existingFile << data << endl;
            existingFile.close();
        }
    }
}

// Function to parse sensor data and write to appropriate log files
void parseAndWriteMAC(const string& csvData) {
    istringstream iss(csvData);

    string line;
    while (getline(iss, line)) {
        istringstream lineStream(line);
        vector<string> tokens;
        string token;
        while (getline(lineStream, token, ',')) {
            tokens.push_back(token);
        }

        if (tokens.size() >= 2) {
            string macAddress = tokens[1];
            auto it = macFiles.find(macAddress);
            if (it == macFiles.end()) {
                // New MAC address, create a new file stream and call writeToLog
                ofstream newFile;
                macFiles[macAddress] = move(newFile);
                writeToLog(macAddress, line);
            }
            else {
                // Existing MAC address, write to the existing file stream and call writeToLog
                writeToLog(macAddress, line);
            }
        }
    }
}

int main() {
    // Initialize the postgresql database
    //setupDatabase();

    // Show me the ip address (maybe save it in a variable for later)
    try {
        io_context io_context;
        tcp::resolver resolver(io_context);
        tcp::resolver::query query(host_name(), "");
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        tcp::resolver::iterator end;

        while (endpoint_iterator != end) {
            tcp::endpoint endpoint = *endpoint_iterator++;
            if (endpoint.address().is_v4()) {
                cout << "Please ensure port forwarding from external IP to local IP " << endpoint.address().to_string() << " is enabled." << endl;
                cout << "Please ensure your board WiFi and external IP are configured." << endl;
                cout << "Example: Board(s) configured to report to external IP 111.222.333.444\n    Local machine IP address is " << endpoint.address().to_string() << ", and for that local IP:\n    External IP start port: 8080, external IP end port: 277\n    Local IP start port: 277, local IP end port to land on this server:" << portVal << endl;
                break;
            }
        }
    }
    catch (exception& e) {
        cerr << "Exception: " << e.what() << endl;
    }

    // Set up the server to accept the sensor transmissions from
    try {
        io_context io_context;

        // Create an acceptor to listen for new connections
        tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), portVal));

        cout << "Server listening on 0.0.0.0 local end port " << portVal << "\n" << endl;

        while (true) {
            // Wait for a new connection
            tcp::socket socket(io_context);
            acceptor.accept(socket);

            cout << "Connection from: " << socket.remote_endpoint().address().to_string() << endl;

            // Receive data from the client
            asio::streambuf buffer;
            asio::read_until(socket, buffer, "\n");
            string data = buffer_cast<const char*>(buffer.data());

            // Setup the time report to add to the sensor data
            time_t now;
            time(&now);
            struct tm tm_info;
            localtime_s(&tm_info, &now);
            char timeBuffer[15];
            strftime(timeBuffer, sizeof(timeBuffer), "%d%m%Y%H%M%S", &tm_info);
            stringstream ss;
            ss << timeBuffer << "," << data;

            // pkg holds time,mac,sensorvalue
            string pkg = ss.str();
            cout << pkg << endl;

            // Send data to csv file (Per unique mac)
            parseAndWriteMAC(pkg);

            // TODO: Send data to the database
            //saveToDatabase(pkg);
        }
    }
    catch (std::exception& e) {
        cerr << "Exception: " << e.what() << endl;
    }

    return 0;
}