import json
import random

import flask

from . import core

## \brief Rolls a random integer between `min` and `max`, and applies all described `modifiers`.
#  \param min The lowest possible number. Default is 0.
#  \param max The highest possible number. Default is 100.
#  \param modifiers
#  \return The result of the dice roll, after modifiers.
#  
#  Dice roll is actually a slight misnomer; the game primarily uses percentages for chance
#  calculations. However, the recognized term for these chance calculations, "dice rolls",
#  is D&D old, so is used here for mental ease.
def dice_roll(min=0, max=100, modifiers=[]):
    result = random.randint(min, max)
    for _, mod in modifiers:
        result += mod
    
    return result

def calculate_speed(agl):
    return 3+(agl * 1.5)

## \brief Attempts to steal a given resource from a target.
#  \param resource The resource to steal.
#  \param target The class of target to steal from.
#  \api{POST} /act/steal/`<resource>`/`<target>`
#  \apidata Gamestate.
@core.app.route("/act/steal/<resource>/<target>", methods=["POST"])
def steal_resource(resource, target):
    core.log.debug(flask.request.get_data())
    gamestate = flask.request.get_json()["gamestate"]
    agl = gamestate["agility"]
    roll = dice_roll()
    speed = calculate_speed(agl)
    result = (roll + speed) + (agl/4)
    return flask.Response(json.dumps({
        "success": (result >= 50)
    }), status=200, content_type="application/json")

## \brief Attempts to recruit a seagull.
#  \api{POST} /act/recruit
#  \apidata Gamestate.
@core.app.route("/act/recruit", methods=["POST"])
def recruit():
    return flask.Response(json.dumps({
        "success": (dice_roll() >= 65)
    }), status=200, content_type="application/json")