//:: OnUsed script for casino math game placeable
//:: Checks for token, difficulty, and starts the game by spawning fish
//:: nw_casino_math_start.nss

const string TOKEN_TAG = "casino_token";       // Tag of the token item
const string VAR_DIFFICULTY = "INT_DIFFICULTY"; // Local int on token
const string FISH_TEMPLATE = "casino_fish";    // ResRef of the fish creature
const string WAYPOINT_TAG_PREFIX = "iSpawnFishHere";
const int MAX_FISH = 10;

void main()
{
    object oPC = GetLastUsedBy();

    // Ensure it's a player and not a DM or creature
    if (!GetIsPC(oPC) || GetIsDM(oPC))
        return;

    // 1. Check for casino token in inventory
    object oToken = GetItemPossessedBy(oPC, TOKEN_TAG);
    if (!GetIsObjectValid(oToken))
    {
        SendMessageToPC(oPC, "You need a casino token to play.");
        return;
    }

    // 2. Check difficulty setting
    int nDifficulty = GetLocalInt(oToken, VAR_DIFFICULTY);
    if (nDifficulty < 1 || nDifficulty > 3)
    {
        SendMessageToPC(oPC, "You must set a difficulty before playing. Use your casino token to choose a difficulty.");
        return;
    }

    // 3. Generate a random target sum (0?99)
    int nTarget = Random(100);
    SetLocalInt(oPC, "MATH_GAME_TARGET", nTarget);
    SetLocalInt(oPC, "MATH_GAME_CURRENT", 0);

    SendMessageToPC(oPC, "Your target number is: " + IntToString(nTarget));

    // 4. Spawn fish at waypoints
    int i;
    for (i = 1; i <= MAX_FISH; i++)      // ? Valid in NWScript

    {
        string sWPTag = WAYPOINT_TAG_PREFIX + IntToString(i);
        object oWP = GetWaypointByTag(sWPTag);

        if (!GetIsObjectValid(oWP))
            continue;

        // Basic logic for spawning a fish with value 0?9
        int nFishValue = Random(10);
        string sDisplay = IntToString(nFishValue); // Name shown on fish

        // Spawn the fish
        object oFish = CreateObject(OBJECT_TYPE_CREATURE, FISH_TEMPLATE, GetLocation(oWP));

        if (GetIsObjectValid(oFish))
        {
            SetLocalInt(oFish, "FISH_VALUE", nFishValue);
            SetName(oFish, sDisplay);
            SetLocalObject(oFish, "FISH_OWNER", oPC); // Optional for click restrictions
        }
    }
}
