#ifndef FACT_MAIN
#define FACT_MAIN

#include <map>
#include <thread>
#include <functional>

#include "LocalControl.h"
#include "Configuration.h"

namespace Main
{
    void SetupConfiguration(Configuration &conf)
    {
        const string n = conf.GetName()+".log";

        po::options_description config("Program options");
        config.add_options()
            ("dns",        var<string>("localhost"),       "Dim nameserver (overwites DIM_DNS_NODE environment variable)")
            ("host",       var<string>(""),                "Address with which the Dim nameserver can connect to this host (overwites DIM_HOST_NODE environment variable)")
            ("log,l",      var<string>(n), "Name of local log-file")
            ("append-log", po_bool(),      "Append log information to local log-file")
            ("null",       po_switch(),    "Suppresses almost all console output - including errors (only available without --console option)")
            ("console,c",  var<int>(),     "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
            ("cmd",        vars<string>(), "Execute one or more commands at startup")
            ("exec,e",     vars<string>(), "Execute one or more scrips at startup")
            ("quit",       po_switch(),    "Quit after startup");
        ;

        conf.AddEnv("dns",  "DIM_DNS_NODE");
        conf.AddEnv("host", "DIM_HOST_NODE");

        conf.AddOptions(config);
    }

    template<class T>
    void PrintHelp()
    {
        Dim::Setup();

        ofstream fout("/dev/null");

        T io_service(fout);

        io_service.PrintListOfStates(cout);
        cout << "\nList of available commands:\n";
        io_service.PrintListOfEvents(cout);
        cout << "\n";
    }

    void Thread(StateMachineImp *io_service, bool dummy)
    {
        // This is necessary so that the StateMachien Thread can signal the
        // Readline to exit
        io_service->Run(dummy);
        Readline::Stop();
    }

    template<class T, class S>
    int execute(Configuration &conf, bool dummy=false)
    {
        Dim::Setup(conf.Get<string>("dns"), conf.Get<string>("host"));

        // -----------------------------------------------------------------

        static T shell(conf.GetName().c_str(),
                       conf.Has("console") ? conf.Get<int>("console")!=1 : conf.Get<bool>("null"));

        WindowLog &win  = shell.GetStreamIn();
        WindowLog &wout = shell.GetStreamOut();

        // Switching off buffering is not strictly necessary, since
        // the destructor of shell should flush everything still buffered,
        // nevertheless it helps to debug problems in the initialization
        // sequence.
        const bool backlog = wout.GetBacklog();
        const bool null    = wout.GetNullOutput();
        if (conf.Has("console") || !conf.Get<bool>("null"))
        {
            wout.SetBacklog(false);
            wout.SetNullOutput(false);
            wout.Display(true);
        }

        if (conf.Has("log"))
            if (!wout.OpenLogFile(conf.Get<string>("log"), conf.Get<bool>("append-log")))
                win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;

        S io_service(wout);

        const boost::filesystem::path path(conf.GetName());

        const string pname = path.parent_path().string();
        const string fname = path.filename();

        const Time now;
        io_service.Write(now, "/----------------------- Program ------------------------");
        io_service.Write(now, "| Program:  "PACKAGE_STRING" ("+fname+")");
        io_service.Write(now, "| CallPath: "+pname);
        io_service.Write(now, "| Compiled: "__DATE__" "__TIME__);
        io_service.Write(now, "| Revision: "REVISION);
        io_service.Write(now, "| Contact:  "PACKAGE_BUGREPORT);
        io_service.Write(now, "| URL:      "PACKAGE_URL);
        io_service.Write(now, "| Start:    "+now.GetAsStr("%c"));
        io_service.Write(now, "\\----------------------- Options ------------------------");
        const multimap<string,string> mmap = conf.GetOptions();
        for (multimap<string,string>::const_iterator it=mmap.begin(); it!=mmap.end(); it++)
            io_service.Write(now, ": "+it->first+(it->second.empty()?"":" = ")+it->second);
        io_service.Write(now, "\\------------------- Evaluating options -----------------");
        const int rc = io_service.EvalOptions(conf);
        if (rc>=0)
        {
            ostringstream str;
            str << "Exit triggered by EvalOptions with rc=" << rc;
            io_service.Write(now, str.str(), MessageImp::kError);
            return rc;
        }

        const map<string,string> &wco = conf.GetWildcardOptions();
        if (wco.size()>0)
        {
            io_service.Write(now, "------------- Unrecognized wildcard options -------------", MessageImp::kWarn);

            size_t max = 0;
            for (map<string,string>::const_iterator it=wco.begin(); it!=wco.end(); it++)
                if (it->second.length()>max)
                    max = it->second.length();

            for (map<string,string>::const_iterator it=wco.begin(); it!=wco.end(); it++)
            {
                ostringstream str;
                str.setf(ios_base::left);
                str << setw(max+1) << it->second << " : " << it->first;
                io_service.Write(now, str.str(), MessageImp::kWarn);
            }
            io_service.Write(now, "Unrecognized options found, will exit with rc=127", MessageImp::kError);
            return 127;
        }

        io_service.Message("==================== Starting main loop =================");

        if (conf.Has("console") || !conf.Get<bool>("null"))
        {
            wout.SetNullOutput(null);
            wout.SetBacklog(backlog);
        }

        shell.SetReceiver(io_service);

        //    boost::thread t(boost::bind(&AutoScheduler<S>::Run, &io_service));
        thread t(bind(Main::Thread, &io_service, dummy));

        const vector<string> v1 = conf.Vec<string>("cmd");
        for (vector<string>::const_iterator it=v1.begin(); it!=v1.end(); it++)
            shell.ProcessLine(*it);

        const vector<string> v2 = conf.Vec<string>("exec");
        for (vector<string>::const_iterator it=v2.begin(); it!=v2.end(); it++)
            shell.Execute(*it);

        if (conf.Get<bool>("quit"))
            shell.Stop();

        shell.Run();                 // Run the shell
        io_service.Stop();           // Signal Loop-thread to stop
        // io_service.Close();       // Obsolete, done by the destructor
        // wout << "join: " << t.timed_join(boost::posix_time::milliseconds(0)) << endl;

        // Wait until the StateMachine has finished its thread
        // before returning and destroying the dim objects which might
        // still be in use.
        t.join();

        return 0;
    }
}

#endif
