//:://////////////////////////////////////////////
//:: Anima Mage Exploit Vestige Spell choice script
//:: bnd_exploitcnv
//:://////////////////////////////////////////////
/** @file
    @author Stratovarius - 2019.02.14
*/
//:://////////////////////////////////////////////
//:://////////////////////////////////////////////

#include "prc_inc_function"
#include "bnd_inc_bndfunc"
#include "inc_dynconv"

//////////////////////////////////////////////////
/* Constant defintions                          */
//////////////////////////////////////////////////

const int STAGE_SELECT_EVOCATION       = 0;
const int STAGE_CONFIRM_SELECTION      = 1;

const int CHOICE_BACK_TO_LSELECT    = -1;

const int STRREF_BACK_TO_LSELECT    = 16836035; // "Return to level selection."
const int STRREF_MYSTLIST_HEADER2   = 16836038; // "more mysteries"
const int STRREF_SELECTED_HEADER1   = 16824209; // "You have selected:"
const int STRREF_SELECTED_HEADER2   = 16824210; // "Is this correct?"
const int STRREF_END_CONVO_SELECT   = 16824212; // "Finish"
const int LEVEL_STRREF_START        = 16824809;
const int STRREF_YES                = 4752;     // "Yes"
const int STRREF_NO                 = 4753;     // "No"

const int SORT       = TRUE; // If the sorting takes too much CPU, set to FALSE
const int DEBUG_LIST = FALSE;

//////////////////////////////////////////////////
/* Function defintions                          */
//////////////////////////////////////////////////

void PrintList(object oBinder)
{
    string tp = "Printing list:\n";
    string s = GetLocalString(oBinder, "PRC_MystConvo_List_Head");
    if(s == ""){
        tp += "Empty\n";
    }
    else{
        tp += s + "\n";
        s = GetLocalString(oBinder, "PRC_MystConvo_List_Next_" + s);
        while(s != ""){
            tp += "=> " + s + "\n";
            s = GetLocalString(oBinder, "PRC_MystConvo_List_Next_" + s);
        }
    }

    DoDebug(tp);
}

/**
 * Creates a linked list of entries that is sorted into alphabetical order
 * as it is built.
 * Assumption: mystery names are unique.
 *
 * @param oBinder     The storage object aka whomever is gaining powers in this conversation
 * @param sChoice The choice string
 * @param nChoice The choice value
 */
void AddToTempList(object oBinder, string sChoice, int nChoice)
{
    if(DEBUG_LIST) DoDebug("\nAdding to temp list: '" + sChoice + "' - " + IntToString(nChoice));
    if(DEBUG_LIST) PrintList(oBinder);
    // If there is nothing yet
    if(!GetLocalInt(oBinder, "PRC_MystConvo_ListInited"))
    {
        SetLocalString(oBinder, "PRC_MystConvo_List_Head", sChoice);
        SetLocalInt(oBinder, "PRC_MystConvo_List_" + sChoice, nChoice);

        SetLocalInt(oBinder, "PRC_MystConvo_ListInited", TRUE);
    }
    else
    {
        // Find the location to instert into
        string sPrev = "", sNext = GetLocalString(oBinder, "PRC_MystConvo_List_Head");
        while(sNext != "" && StringCompare(sChoice, sNext) >= 0)
        {
            if(DEBUG_LIST) DoDebug("Comparison between '" + sChoice + "' and '" + sNext + "' = " + IntToString(StringCompare(sChoice, sNext)));
            sPrev = sNext;
            sNext = GetLocalString(oBinder, "PRC_MystConvo_List_Next_" + sNext);
        }

        // Insert the new entry
        // Does it replace the head?
        if(sPrev == "")
        {
            if(DEBUG_LIST) DoDebug("New head");
            SetLocalString(oBinder, "PRC_MystConvo_List_Head", sChoice);
        }
        else
        {
            if(DEBUG_LIST) DoDebug("Inserting into position between '" + sPrev + "' and '" + sNext + "'");
            SetLocalString(oBinder, "PRC_MystConvo_List_Next_" + sPrev, sChoice);
        }

        SetLocalString(oBinder, "PRC_MystConvo_List_Next_" + sChoice, sNext);
        SetLocalInt(oBinder, "PRC_MystConvo_List_" + sChoice, nChoice);
    }
}

/**
 * Reads the linked list built with AddToTempList() to AddChoice() and
 * deletes it.
 *
 * @param oBinder A PC gaining powers at the moment
 */
void TransferTempList(object oBinder)
{
    string sChoice = GetLocalString(oBinder, "PRC_MystConvo_List_Head");
    int    nChoice = GetLocalInt   (oBinder, "PRC_MystConvo_List_" + sChoice);

    DeleteLocalString(oBinder, "PRC_MystConvo_List_Head");
    string sPrev;

    if(DEBUG_LIST) DoDebug("Head is: '" + sChoice + "' - " + IntToString(nChoice));

    while(sChoice != "")
    {
        // Add the choice
        AddChoice(sChoice, nChoice, oBinder);

        // Get next
        sChoice = GetLocalString(oBinder, "PRC_MystConvo_List_Next_" + (sPrev = sChoice));
        nChoice = GetLocalInt   (oBinder, "PRC_MystConvo_List_" + sChoice);

        if(DEBUG_LIST) DoDebug("Next is: '" + sChoice + "' - " + IntToString(nChoice) + "; previous = '" + sPrev + "'");

        // Delete the already handled data
        DeleteLocalString(oBinder, "PRC_MystConvo_List_Next_" + sPrev);
        DeleteLocalInt   (oBinder, "PRC_MystConvo_List_" + sPrev);
    }

    DeleteLocalInt(oBinder, "PRC_MystConvo_ListInited");
}

int GetHighestSpellLevel(object oBinder)
{
	if (!GetLocalInt(oBinder, "PRC_ArcSpell"+IntToString(9))) return 9;
	else if (!GetLocalInt(oBinder, "PRC_ArcSpell"+IntToString(8))) return 8;
	else if (!GetLocalInt(oBinder, "PRC_ArcSpell"+IntToString(7))) return 7;
	else if (!GetLocalInt(oBinder, "PRC_ArcSpell"+IntToString(6))) return 6;
	else if (!GetLocalInt(oBinder, "PRC_ArcSpell"+IntToString(5))) return 5;
	else if (!GetLocalInt(oBinder, "PRC_ArcSpell"+IntToString(4))) return 4;
	else if (!GetLocalInt(oBinder, "PRC_ArcSpell"+IntToString(3))) return 3;
	
	// Need 2 to get into the class
	return 2;
}

void main()
{
    object oBinder = GetPCSpeaker();
    int nValue = GetLocalInt(oBinder, DYNCONV_VARIABLE);
    int nStage = GetStage(oBinder);
   	int nType = GetPrimaryArcaneClass(oBinder);   
   	string sPowerFile = GetFileForClass(nType);
   	if (nType = CLASS_TYPE_WIZARD) sPowerFile = "cls_spell_sorc";

    // Check which of the conversation scripts called the scripts
    if(nValue == 0) // All of them set the DynConv_Var to non-zero value, so something is wrong -> abort
        return;

    if(nValue == DYNCONV_SETUP_STAGE)
    {
        if(DEBUG) DoDebug("bnd_exploitcnv: Running setup stage for stage " + IntToString(nStage));
        // Check if this stage is marked as already set up
        // This stops list duplication when scrolling
        if(!GetIsStageSetUp(nStage, oBinder))
        {
            if(DEBUG) DoDebug("bnd_exploitcnv: Stage was not set up already");
            // mystery selection stage
            if(nStage == STAGE_SELECT_EVOCATION)
            {
                if(DEBUG) DoDebug("bnd_exploitcnv: Building spell selection");

                SetHeader("Select a spell to store for Exploit Vestige");

                int nLevelToBrowse = GetHighestSpellLevel(oBinder);

                if(DEBUG)
                {
                	DoDebug("bnd_exploitcnv: Spell Level To Browse: " + IntToString(nLevelToBrowse));
                }

                int i, nSpellLevel;
                string sFeatID;
                for(i = 0; i < 600 ; i++)
                {
                    nSpellLevel = StringToInt(Get2DACache(sPowerFile, "Level", i));
                    // Skip any powers of too low level
                    if(nSpellLevel < nLevelToBrowse){
                        continue;
                    }
                     //Due to the way the 2das are structured, we know that once
                     //the level of a read spell is greater than the maximum castable
                     //it'll never be lower again. Therefore, we can skip reading the
                     //spells that wouldn't be shown anyway.
                     
                    if(nSpellLevel > nLevelToBrowse){
                        break;
                    }
                    sFeatID = Get2DACache(sPowerFile, "FeatID", i);
                    int nSpellId = StringToInt(Get2DACache(sPowerFile, "RealSpellID", i));
                    if(sFeatID != "") // Non-blank row
                    {
                        if(SORT) AddToTempList(oBinder, GetStringByStrRef(StringToInt(Get2DACache("spells", "Name", nSpellId))), nSpellId);
                        else     AddChoice(GetStringByStrRef(StringToInt(Get2DACache("spells", "Name", nSpellId))), nSpellId, oBinder);
                    }
                }

                if(SORT) TransferTempList(oBinder);

                // Hack - In the mystery selection stage, on returning from
                // confirmation dialog where the answer was "No", restore the
                // offset to be the same as on entering the confirmation dialog.
                if(GetLocalInt(oBinder, "MYSTLISTChoiceOffset"))
                {
                    if(DEBUG) DoDebug("bnd_exploitcnv: Running offset restoration hack");
                    SetLocalInt(oBinder, DYNCONV_CHOICEOFFSET, GetLocalInt(oBinder, "MYSTLISTChoiceOffset") - 1);
                    DeleteLocalInt(oBinder, "MYSTLISTChoiceOffset");
                }

                MarkStageSetUp(STAGE_SELECT_EVOCATION, oBinder);
            }
            // Selection confirmation stage
            else if(nStage == STAGE_CONFIRM_SELECTION)
            {
                if(DEBUG) DoDebug("bnd_exploitcnv: Building selection confirmation");
                // Build the confirmantion query
                string sToken = GetStringByStrRef(STRREF_SELECTED_HEADER1) + "\n\n"; // "You have selected:"
                int nSpellId = GetLocalInt(oBinder, "nEvo");
                sToken += GetStringByStrRef(StringToInt(Get2DACache("spells", "Name", nSpellId)))+"\n";
                sToken += GetStringByStrRef(StringToInt(Get2DACache("spells", "SpellDesc", nSpellId)))+"\n\n";
                sToken += GetStringByStrRef(STRREF_SELECTED_HEADER2); // "Is this correct?"
                SetHeader(sToken);

                AddChoice(GetStringByStrRef(STRREF_YES), TRUE, oBinder); // "Yes"
                AddChoice(GetStringByStrRef(STRREF_NO), FALSE, oBinder); // "No"
            }
        }

        // Do token setup
        SetupTokens();
    }
    else if(nValue == DYNCONV_EXITED)
    {
        if(DEBUG) DoDebug("bnd_exploitcnv: Running exit handler");
        // End of conversation cleanup
        DeleteLocalInt(oBinder, "nClass");
        DeleteLocalInt(oBinder, "nEvo");
        DeleteLocalInt(oBinder, "nLevelToBrowse");
        DeleteLocalInt(oBinder, "MYSTLISTChoiceOffset");
    }
    else if(nValue == DYNCONV_ABORTED)
    {
        // This section should never be run, since aborting this conversation should
        // always be forbidden and as such, any attempts to abort the conversation
        // should be handled transparently by the system
    }
    // Handle PC response
    else
    {
        int nChoice = GetChoice(oBinder);
        if(DEBUG) DoDebug("bnd_exploitcnv: Handling PC response, stage = " + IntToString(nStage) + "; nChoice = " + IntToString(nChoice) + "; choice text = '" + GetChoiceText(oBinder) +  "'");
        if(nStage == STAGE_SELECT_EVOCATION)
        {
            if(DEBUG) DoDebug("bnd_exploitcnv: Entering mystery confirmation");
            SetLocalInt(oBinder, "nEvo", nChoice);
            // Store offset so that if the user decides not to take the mystery,
            // we can return to the same page in the mystery list instead of resetting to the beginning
            // Store the value +1 in order to be able to differentiate between offset 0 and undefined
            SetLocalInt(oBinder, "MYSTLISTChoiceOffset", GetLocalInt(oBinder, DYNCONV_CHOICEOFFSET) + 1);
            nStage = STAGE_CONFIRM_SELECTION;

            MarkStageNotSetUp(STAGE_SELECT_EVOCATION, oBinder);
        }
        else if(nStage == STAGE_CONFIRM_SELECTION)
        {
        	if (nChoice)
        	{
        	    SetLocalInt(oBinder, "ExploitVestigeSpell", GetLocalInt(oBinder, "nEvo"));
            	// And we're all done
            	AllowExit(DYNCONV_EXIT_FORCE_EXIT); 
            }
            else
           	{
            	nStage = STAGE_SELECT_EVOCATION;
            	MarkStageNotSetUp(STAGE_SELECT_EVOCATION, oBinder);           	
           	}
        }

        if(DEBUG) DoDebug("bnd_exploitcnv: New stage: " + IntToString(nStage));

        // Store the stage value. If it has been changed, this clears out the choices
        SetStage(nStage, oBinder);
    }
}
