#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <map>
#include <set>
#include <vector>
#include <list>
#include <memory>
#include <streambuf>
#include <deque>
#include "CJsonObject/CJsonObject.hpp"
using namespace std;
typedef map<string,string> Event;
struct EventsContainer{
const Event PopEvent() {
if( events.empty()) {
cout << "Empty Event queue" << endl;
return Event();
}
Event tmp = events.front();
events.pop_front();
return tmp;
}
void AddEvent(const string& evenname, const map<string,string>& param) {
AddEvent(param);
}
void AddEvent(const Event& event) {
events.push_back(event);
}
deque<Event> events;
};
class EventSequence{
public:
EventSequence() {
}
const Event GetEvent(){
return container->PopEvent();
}
void SetEventsContainer(shared_ptr<EventsContainer> ptr) {
container = ptr;
}
private:
shared_ptr<EventsContainer> container;
};
class EventsInitializer{
public:
shared_ptr<EventSequence> operator()(const std::string& file) {
shared_ptr<EventSequence> esptr = make_shared<EventSequence>();
shared_ptr<EventsContainer> ecptr = make_shared<EventsContainer>();
esptr->SetEventsContainer(ecptr);
container = ecptr;
ReadJsonFile(file);
return esptr;
}
void ReadJsonFile( const string& file) {
ifstream f (file.c_str());
if( f.is_open()) {
jsonstr = string(istreambuf_iterator<char>(f), istreambuf_iterator<char>());
json = make_shared<neb::CJsonObject>(jsonstr);
cout << "JSON error msg -->" << json->GetErrMsg() << endl;
Parse();
return;
}
cout << "ERROR---->File Not ok, Plase Check File....." << endl;
}
virtual void Parse() {
for( int i = 0; i < (*json)["events"].GetArraySize(); ++i) {
map<string,string> tmp;
while(true) {
string key;
string value;
(*json)["events"][i].GetKey(key);
if ( key.empty() ) break;
(*json)["events"][i].Get(key, value);
tmp[key] = value;
}
container->AddEvent(tmp["event"], tmp);
}
cout << "Json Parsing Ok...." << endl;
}
private:
string jsonstr;
shared_ptr<neb::CJsonObject> json;
shared_ptr<EventsContainer> container;
};
class CallObject{
public:
virtual void operator()(const Event& event) {
string ename = (event.find("event")== event.end())?"":(event.find("event"))->second;
cout << "event:" << ename << endl;
for( map<string,string>::const_iterator itr = event.begin();
itr != event.end(); ++itr ) {
cout << "+->" <<itr->first << ":" << itr->second << endl;
}
}
};
class ActionControler{
public:
ActionControler(shared_ptr<EventSequence> ptr) {
SetEventSequence(ptr);
}
void SetEventSequence(shared_ptr<EventSequence> ptr) {
sequence = ptr;
}
void run(CallObject& call) {
char tmp;
while( cin.get(tmp)) {
switch( tmp ) {
case '\n':
call(sequence->GetEvent());
break;
default:
break;
}
}
}
private:
std::shared_ptr<EventSequence> sequence;
};
int main(int argc, char** argv) {
shared_ptr<EventSequence> eventsequence = EventsInitializer()(argv[1]);
ActionControler ac(eventsequence);
CallObject callme;
ac.run(callme);
return -1;
}