//
//  presetManager.mm
//  oscSenderExample
//
//  Created by Robert Tubb on 07/11/2012.
//
//

#include "presetManager.h"

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

extern EventLogger eventLogger;


//---------------------------------------------------------------------------
Json::Value Preset::presetToJson(){
    // create the string for this instance of Preset object
    
    Json::Value presetVal;
    
    presetVal["creatorUserName"] =  creatorUserName;
    presetVal["creatorDeviceID"] =  creatorDeviceID;
    presetVal["creationTime"] =     creationTime;
    presetVal["name"] =             name;
    presetVal["imageFileName"] =    imageFileName;

    for(vector<int>::iterator i = CCValues.begin(); i < CCValues.end(); i++){
        int c = *i;
        presetVal["CCValues"].append(c);
    }

    return presetVal;
}
//---------------------------------------------------------------------------
PresetManager::PresetManager(){
    timesOpened = 0;
    nextID = 0;
   
    string ts = ofGetTimestampString();
    
    presetAlertShowing = false;

    
    cout << "ofGetTimestampString: " << ts << '\n';
}
//---------------------------------------------------------------------------
Json::Value PresetManager::allPresetsToJson(){
    Json::Value root;
 
    // use jsoncpp
    vector<Preset *>::iterator presetIter;
    
    int i = 0;
    for(presetIter = thePresets.begin(); presetIter < thePresets.end(); presetIter++){
        root["presets"][i] = (*presetIter)->presetToJson();
        i++;
    }

    return root;
}
//---------------------------------------------------------------------------
void PresetManager::loadPresetsFromJsonFile(const string &jsonFile){
    Json::Value root;
    Json::Reader reader;

    
    ifstream theFile(jsonFile.c_str());
    stringstream fileText;
    string line;
    if(!theFile){
        cout<<"can't find preset file \n";
        return;
    }else{
        
        while(theFile){
            theFile >> line;
            // cout << line << "\n"; // lots?
            fileText << line;
            
        }
        
        theFile.close();
    }
    
    bool parsingSuccessful = reader.parse( fileText.str(), root );

    if ( !parsingSuccessful )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << "Failed to parse preset JSON: \n"
        << reader.getFormattedErrorMessages();
        return;
    }

    // now put into variables
    const Json::Value jpresets = root["presets"];
    
    for ( int index = 0; index < jpresets.size(); ++index ) thePresets.push_back(new Preset(jpresets[index]));

     
}
//---------------------------------------------------------------------------
void PresetManager::printAll(){
    cout << "----------------ALL PRESETS-------------: \n";
    cout << allPresetsToJson() << "\n";
}
//---------------------------------------------------------------------------
void PresetManager::showNameDialog(){
//    if(!presetAlertViewController.alertShowing){ // this is to stop wierd infinite loop in ios5 (simulator)
//        presetAlertShowing = true;
//        [presetAlertViewController showPresetNamePrompt];
//        
//    }
    
}
//---------------------------------------------------------------------------
// when save button pressed
void PresetManager::savePreset(const string name, vector<int> values){

    presetAlertShowing = false;
    // check for same name
    vector<Preset *>::iterator iter;

    for(iter = thePresets.begin(); iter < thePresets.end(); iter++){
        if ((*iter)->name == name){
            cout << "WARNING Preset by that name exists, overwriting\n";
            // overwrite it
            (*iter)->setValues(values);
            updatePresetFile();
            eventLogger.logEvent(SAVE_PRESET); // TODO need to log details?
            return;
        }
    }
     
    if(name == ""){
        cout << "Please name preset\n";
        
    }

    thePresets.push_back(new Preset(values, name, nextID, eventLogger.userName, eventLogger.deviceID));
    eventLogger.logEvent(SAVE_PRESET); // TODO need to log details?
    updatePresetFile();

}
//-----------------------------------------------------------------------------
void PresetManager::generatePresetSlot(const string name, const string imagefn){
    vector<int> values; // empty
    thePresets.push_back(new Preset(values, name, nextID, eventLogger.userName, eventLogger.deviceID, imagefn));
    
}
//----------------------------------------------cu-----------------------------
vector<int> PresetManager::recallPreset(string name){
    vector<Preset *>::iterator p;
    for(p = thePresets.begin(); p < thePresets.end(); p++){
        if ( (*p)->getName() == name){
            return (*p)->getValues();
        }
    }
    vector<int> empty;
    return empty;
}
//----------------------------------------------cu-----------------------------
void PresetManager::startLoadAll(){

    presetFileName = ofxiPhoneGetDocumentsDirectory() + PRESET_FILENAME;
    
    loadPresetsFromJsonFile(presetFileName);
    
    timesOpened++;
}
//---------------------------------------------------------------------------
void PresetManager::updatePresetFile(){
    
    // TODO really inefficient
    
    ofFile presetFile(presetFileName,ofFile::WriteOnly);

    // stick all the stuff in a json value
    Json::Value root = allPresetsToJson();

    presetFile << root;
}
//---------------------------------------------------------------------------
void PresetManager::exitAndSaveAll(){
    updatePresetFile();

}

//---------------------------------------------------------------------------
void PresetManager::clearAll(){
    thePresets.clear();
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------