//
//  TrainingMessageOrganiser.mm
//  riftathon
//
//  Created by Robert Tubb on 17/10/2014.
//
//

#include "TrainingMessageOrganiser.h"

void TrainingMessageOrganiser::init( PDSynthWrapper& cs, PDSynthWrapper& ts){
    
    MessageOrganiser::init(cs,ts);
    
    TickListenerFunction callback;
    callback = boost::bind(&TrainingMessageOrganiser::onNextTickAnim, this, _1);
    candidateSynth.registerForTicks(callback);
    
    numParamsToUse = TOTAL_NUM_PARAMS;
    
}

void TrainingMessageOrganiser::setup(controlPanelType whichInterfaceAreWeUsing){
    
    setupDefaultMapping(whichInterfaceAreWeUsing);
    
    controlPanel->setValues(zeros<int>(TOTAL_NUM_PARAMS));
}
//----------------------------------------------------------------------------------------
void TrainingMessageOrganiser::setMiddlePanel(TextPanel* tp){
    middlePanel = tp;
}

//----------------------------------------------------------------------------------------
void TrainingMessageOrganiser::showMyPanels(){
    presetIconPanel->show();
    instructionPanel->show();
    bottomPanel->show();
    controlPanel->show();
    middlePanel->show();
}

//-----------------------------------------------------------------------
void TrainingMessageOrganiser::displayInstructions(string text){

    instructionPanel->setText(text);
    instructionPanel->show();

}

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

void TrainingMessageOrganiser::showUserHowTheyDid(){
    // colour flash
    // distance ?
    // score
    
}

//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::midiFromLeap(int ctl_num, int ctl_val){
    
    if (!okToGetMidi){
        return;
    }
    vector<int> mids = candidateSynth.getAllMappingIDs();
    if (ctl_num >= mids.size() || ctl_num < 0) return;
    
    paramChangeCallback(mids[ctl_num], ctl_val );
    
    //candidateSynth.paramChangeCallback(mids[ctl_num], ctl_val);
    
    setUIToParam(ctl_num, ctl_val);
    
    vector<int> evtData;
    evtData.push_back(mids[ctl_num]); // or just index?
    evtData.push_back(ctl_val);
    
    eventLogger.logEvent(CANDIDATE_PARAM_ADJUSTED, evtData);
    
}
//-----------------------------------------------------------------------------

void TrainingMessageOrganiser::buttonPressCallback(int mappingID, int value){
    if(mappingID == VOLUME_CHANGE_ID){
        targetSynth.sendVolume(value);
        candidateSynth.sendVolume(value);
        return;
    }
    
    if (mappingID == START_TRAINING_SEQUENCE_ID){
        //triggerCandidateSound();
        // compare to target
        candidateSynth.setMetroTime(sequenceController.getStartTickTime());
        candidateSynth.startMetronome();
        bottomPanel->hide();
        return;
    }
    
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------
void TrainingMessageOrganiser::onNextTick(int tickNumber){
    static int showingCountdown = false;

    downCounter = 4 - tickNumber % 4;
    
    if (showingCountdown){
        middlePanel->setColor(ofColor::white);
        middlePanel->setText(ofToString(downCounter));
    }
    
    // only first beat in bar is active one
    if ( tickNumber % 4  != 0){
        
        return;
    }
    
}
void TrainingMessageOrganiser::lastOfRun(){
    candidateSynth.stopMetronome();
    cout << "FINISHED RUN" << endl;
    controlPanel->hide();
    middlePanel->setColor(ofColor::white);
    middlePanel->setText("FINISHED RUN");
    middlePanel->show();
    bottomPanel->show();
}
void TrainingMessageOrganiser::lastOfAll(){
    candidateSynth.stopMetronome();
    cout << "FINISHED BLOCK" << endl;
    controlPanel->hide();
    middlePanel->setColor(ofColor::white);
    middlePanel->setText("FINISHED BLOCK");
    middlePanel->show();
    bottomPanel->show();
}
//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::onNextTickAnim(int tickNumber){
    static AnimStep oldStep;
    static vector<int> lastPosition;
    
    cout << "TICK " << tickNumber << endl;
    downCounter = 4 - tickNumber % 4;
    
    updateCountdown(downCounter);
    // only first beat in bar is active one (at the moment)
    // TODO send next target values again and again
    if ( tickNumber % 4  != 0) {
        if (tickNumber % 4  == 3){
            targetSynth.sendAllParams();
        }
        return;
    };
    
    
    Preset* previousTargetPreset;
    vector<int> curCandidateSettings = candidateSynth.getAllParamValues();
    if (oldStep.showsResultsAtEnd){
        
        // store results
        if(oldStep.presetIndex == -1){
            previousTargetPreset =  expPresetManager.getNeutralPreset();
            cout << "SHOULDNT SCORE NEUTRAL??" << endl;
        }else{
            
            previousTargetPreset =  expPresetManager.getPresetAtIndex(oldStep.presetIndex);
        }
        previousTargetPreset =  expPresetManager.getPresetAtIndex(oldStep.presetIndex);
        TrainingTestResult result =  doResults(oldStep,
                                               previousTargetPreset,
                                               lastPosition,
                                               curCandidateSettings);
        
        flashResult(result);
    }
    
    AnimStep newStep = sequenceController.getNextStep();
    
    if(newStep.isLastOfAll){
        lastOfAll();
        return;
    }
    if(newStep.isLastOfRun){
        lastOfRun();
        return;
    }
    
    candidateSynth.setMetroTime(newStep.getTimeBetweenTicks());
    
    switch (newStep.type){
        case AnimStep::PREVIEW_NEUTRAL_COUNT :
            previewNeutralCount(newStep);
            break;
        case AnimStep::PREVIEW_MOVE :
            previewMove(newStep);
            break;
        case AnimStep::PREVIEW_HIT :
            previewHit( newStep);
            break;
        case AnimStep::MATCHING_NEUTRAL_COUNT :
            matchingNeutralCount( newStep);
            break;
        case AnimStep::MATCHING_MOVE :
            matchingMove( newStep);
            break;
        case AnimStep::MATCHING_HIT :
            matchingHit( newStep);
            break;
        case AnimStep::GUIDED_MOVE :
            guidedMove( newStep);
            break;
            
        case AnimStep::GUIDED_HIT :
            guidedHit( newStep);
            break;
        default:
            break;
    }
    
    oldStep = newStep;
    lastPosition = curCandidateSettings;
    
}
//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::updateCountdown(int n){
    
}
//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::previewNeutralCount(AnimStep newStep){
    

    middlePanel->hide();
    
    Preset * currentTargetPreset;

    // your 'hand' is hidden
    controlPanel->showValueIndicators(false);
    
    
    // guide is set to neutral values
    currentTargetPreset = expPresetManager.getNeutralPreset();
    vector<int> newTargetValues = currentTargetPreset->getValues();
    presetIconPanel->setTextAndImage(currentTargetPreset->name, currentTargetPreset->getImage(), false);
    presetIconPanel->show();
    controlPanel->setValues(newTargetValues);
    controlPanel->setAndShowHint(newTargetValues, currentTargetPreset->getImage());
    controlPanel->setActive(false);
    
    targetSynth.setAllParams(newTargetValues);
    candidateSynth.setAllParams(newTargetValues);
    
    displayInstructions("preview Neutral Count");
    
    oldTargetValues = newTargetValues;
}
//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::previewMove(AnimStep newStep){
    controlPanel->setValues(oldTargetValues);
    targetSynth.trigger(); // PLAYS LAST TARGET (but it doesn't?)
    Preset * currentTargetPreset;
    if(newStep.presetIndex == -1){
        currentTargetPreset =  expPresetManager.getNeutralPreset();
    }else{
        
        currentTargetPreset =  expPresetManager.getPresetAtIndex(newStep.presetIndex);
    }
    vector<int> newTargetValues = currentTargetPreset->getValues();
    
    targetSynth.setAllParamsWithoutSend(newTargetValues);
    
    // show icon and guides
    presetIconPanel->setTextAndImage(currentTargetPreset->name, currentTargetPreset->getImage(), false);
    if (newStep.showsIcons){
        presetIconPanel->show();
    }else{
        presetIconPanel->hide();
    }
    controlPanel->show();
    
    controlPanel->showValueIndicators(true);
    controlPanel->setActive(false);
    
    // show where we're going
    controlPanel->setAndShowHint(newTargetValues, currentTargetPreset->getImage());
    
    // show how to get there
    controlPanel->animateToNewValues(newTargetValues, newStep.getTimeBetweenTicks()*4);
    displayInstructions("preview Move");
    
    oldTargetValues = newTargetValues;
}
//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::previewHit(AnimStep newStep){
    Preset * currentTargetPreset;
    currentTargetPreset =  expPresetManager.getPresetAtIndex(newStep.presetIndex);
    vector<int> newTargetValues = currentTargetPreset->getValues();
    
    targetSynth.setAllParams(newTargetValues);
    
    // your hand hidden
    controlPanel->showValueIndicators(false);
    //
    presetIconPanel->setTextAndImage(currentTargetPreset->name, currentTargetPreset->getImage(), false);
    presetIconPanel->show();
    
    controlPanel->setAndShowHint(newTargetValues, currentTargetPreset->getImage());

    
    targetSynth.trigger();
    
    displayInstructions("Preview HIT");
}

//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::guidedMove(AnimStep newStep){
    targetSynth.trigger(); // PLAYS LAST TARGET (?)
    
    middlePanel->hide();
    
    Preset * currentTargetPreset;
    if(newStep.presetIndex == -1){
        currentTargetPreset =  expPresetManager.getNeutralPreset();
    }else{
        
        currentTargetPreset =  expPresetManager.getPresetAtIndex(newStep.presetIndex);
    }

    vector<int> newTargetValues = currentTargetPreset->getValues();
    
    targetSynth.setAllParamsWithoutSend(newTargetValues);
    
    
    controlPanel->setActive(true);
    // show icon and guide markers
    presetIconPanel->setTextAndImage(currentTargetPreset->name, currentTargetPreset->getImage(), false);
    presetIconPanel->show();
    
    controlPanel->setAndShowHint(newTargetValues, currentTargetPreset->getImage());
    
    
    // show your hand and allow movement
    controlPanel->showValueIndicators(true);
    okToGetMidi = true;
    
    displayInstructions("GUIDED MOVE");

    oldTargetValues = newTargetValues;
}

//======================================================================
void TrainingMessageOrganiser::guidedHit(AnimStep newStep){
    Preset * currentTargetPreset;
    currentTargetPreset =  expPresetManager.getPresetAtIndex(newStep.presetIndex);
    vector<int> newTargetValues = currentTargetPreset->getValues();
    
    sendSynthValuesAgain();
    
    // show your hand and allow movement (so you can set off to next target??)
    
    controlPanel->showValueIndicators(true);
    okToGetMidi = true;
    
    targetSynth.setAllParamsWithoutSend(newTargetValues);
    triggerCandidateSound();
    
    displayInstructions("GUIDED HIT");
    vector<int> startPosition = expPresetManager.getNeutralPreset()->getValues();
    
    oldTargetValues = newTargetValues;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::matchingNeutralCount(AnimStep newStep){
    Preset * currentTargetPreset = expPresetManager.getNeutralPreset();
    vector<int> newTargetValues = currentTargetPreset->getValues();
    // if showing guides show all the targets as transparent ghosts
    if (newStep.showsGuides){
        controlPanel->setAndShowHint(newTargetValues, currentTargetPreset->getImage());

    }else{
        controlPanel->showHint(false);
    }
    
    // show your hand and allow movement
    controlPanel->showValueIndicators(true);
    okToGetMidi = true;
    
        displayInstructions("Match Count");
    
    oldTargetValues = newTargetValues;
}
//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::matchingMove(AnimStep newStep){

    
    middlePanel->hide();
    
    Preset * currentTargetPreset;
    if(newStep.presetIndex == -1){
        currentTargetPreset =  expPresetManager.getNeutralPreset();
    }else{
        
        currentTargetPreset =  expPresetManager.getPresetAtIndex(newStep.presetIndex);
    }

    vector<int> newTargetValues = currentTargetPreset->getValues();
    
    targetSynth.setAllParams(newTargetValues);

    // if showing guides show the hint hand
    
    if (newStep.showsGuides){
        controlPanel->setHintNoShow(newTargetValues, currentTargetPreset->getImage());
        controlPanel->showHint(true);
    }else{
        //
        controlPanel->showHint(false);
    }
    if (newStep.showsIcons){
        presetIconPanel->setTextAndImage(currentTargetPreset->name, currentTargetPreset->getImage(), false);
        presetIconPanel->show();
    }else{
        presetIconPanel->hide();
    }
    // show your hand and allow movement
    //controlPanel->showIndicator(true);
    okToGetMidi = true;
    
    displayInstructions("Match MOVE");

    // trigger where we're at at the moment
    triggerCandidateSound();

    oldTargetValues = newTargetValues;

}
//-----------------------------------------------------------------------------
void TrainingMessageOrganiser::matchingHit(AnimStep newStep){
    Preset * currentTargetPreset;
    currentTargetPreset =  expPresetManager.getPresetAtIndex(newStep.presetIndex);
    vector<int> newTargetValues = currentTargetPreset->getValues();

    sendSynthValuesAgain();
    
    // show your hand and allow movement (so you can set off to next target??)
    //box6D->showIndicator(true);
    okToGetMidi = true;
    
    targetSynth.setAllParams(newTargetValues);
    triggerCandidateSound();
    
    displayInstructions("Match FINISHED");
    vector<int> startPosition = expPresetManager.getNeutralPreset()->getValues();
    controlPanel->setHintNoShow(newTargetValues, currentTargetPreset->getImage());

    oldTargetValues = newTargetValues;
}
//-----------------------------------------------------------------------------

TrainingTestResult TrainingMessageOrganiser::doResults(AnimStep newStep,
                                                       Preset * targetPreset,
                                                       vector<int> startingPosition,
                                                       vector<int> currentPosition){
    TrainingTestResult result =
    trainingScoreManager.getScoreForAnswer(currentPosition,
                                           startingPosition,
                                           targetPreset->getValues(),
                                           newStep.getTimeBetweenTicks());
    
    sequenceController.saveResultForCurrentStep(result);
    instructionPanel->setColor(result.colorBand);


    displayInstructions(result.displayText);
    
    return result;
}

void TrainingMessageOrganiser::flashResult(TrainingTestResult r){
    
    // stick a colored number over target position
    controlPanel->flashResultLight(r.colorBand, 30);

    
}
