#include "sierrachart.h"
#include <thread>
#include <iostream>
#include <fstream>
#include <ctime>

class Server {

public:
    Server(SCStudyInterfaceRef sc, int debug) : sc(sc), debug(debug) {
        file.open("vol.txt");
    }

    ~Server() {
        file.close();
    }

    void Start() {
        running = true;
        t = std::thread(&Server::Run, this);
        t.detach();
    }

    void Stop() {
        sc.AddMessageToLog("stopping thread", debug);
        running = false;
        t.join();
    }

private:
    SCStudyInterfaceRef sc;
    int debug;
    std::ofstream file;

    std::thread t;
    std::atomic_bool running = false;

    void Run() {
        while (running) {
            sc.AddMessageToLog("started thread", debug);
            time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
            file << std::ctime(&tt) << sc.LastTradePrice << std::endl;
            file.flush();

            std::this_thread::sleep_for(std::chrono::seconds(5));
        }
    }
};

SCDLLName("ThreadServer")
SCSFExport scsf_ThreadServer(SCStudyInterfaceRef sc) {
    
    if (sc.SetDefaults) {
        sc.GraphRegion = 0;
        sc.StudyDescription = "Thread server";
        sc.GraphName = "ThreadServer";
        sc.AutoLoop = 0;
        return;
    }

    Server* server = static_cast<Server*>(sc.GetPersistentPointer(1));

    if (server == NULL) {
        server = new Server(sc, 1);
        server->Start();
        sc.SetPersistentPointer(1, server);
    }

    if (sc.LastCallToFunction) {
        if (server != NULL) {
            server->Stop();
            delete server;
        }
    }

}