#include "stdafx.h"
#include "HCAVM.h"
#include <string>
using std::string;
#include <sstream>
using std::ostream;
using std::ends;
using std::stringstream;

CArchive & operator << (CArchive & ar, 
                        TraversableAVMGame & game) {
    stringstream strout;
    strout << game << ends;
    string gameString = strout.str();
    const char *cp = gameString.c_str();
    while (*cp != '\0') ar << *cp++;
    ar << '\0';
    return ar;
}

CArchive & operator >> (CArchive & ar, 
                        TraversableAVMGame & game) {
    string instring;
    char c;
    ar >> c;
    while (c != '\0') {
        instring += c;
        ar >> c;
    }
    stringstream strin(instring);
    strin >> game;
    game.reset();
    CDocument *pDoc = dynamic_cast<CDocument*>(&game);
    pDoc->SetModifiedFlag();
    return ar;
}

void HCAVMView::onLButtonDown(CPoint p) {
    switch(state) {
    case QUESTIONING:
        if (inRectangle(p,YesBox)) pGame->accept();
        else if (inRectangle(p,NoBox)) pGame->reject();
        if (pGame->atEnd()) state = GAME_OVER;
        else if (pGame->atSubtreeEnd()) 
            state = ASKING_FOR_SUBCATEGORY;
        break;
    case ASKING_FOR_SUBCATEGORY: 
        if (inRectangle(p,YesBox)){
            CNewSubcategoryDialog dlg(0,pGame->getName());
            int rv = dlg.DoModal();
            if (rv == IDOK) {
                string subcategoryName = dlg.getSubcategory();
                string question = dlg.getQuestion();
                pGame->addSubcategory(
                    subcategoryName,question);
            }
            state = OFFERING_NEW_GAME;
        } 
        else if (inRectangle(p,NoBox))
            state = OFFERING_NEW_GAME;
        break;
    case OFFERING_NEW_GAME:
        if (inRectangle(p,YesBox)) {
            pGame->reset();
            state = QUESTIONING;
        }
        else if (inRectangle(p,NoBox)) state = GAME_OVER;
    }
    pWnd->Invalidate();
}
