#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import cgi

from sorcery import dict_of

from lib import api
from lib import errorHandler
from lib.errors import CurangelError
from lib.account_util import Account
from lib.notify_hook import notify


def get_mana(account):
    mana = account.mana.value
    stamina = account.stamina.value
    step = account.stamina.step
    notify("mana-check", dict_of(
        mana,
        stamina,
        step,
        account=account.name
    ))
    return {
        "mana": mana,
        "stamina": {
            "step": step,
            "value": stamina
        }
    }


def main(username, userhash, account):
    requester = Account(username)

    requester.login(userhash)
    if username == account:
        return get_mana(requester)
    else:
        target = Account(account)
        with requester.admin:
            return get_mana(target)


if __name__ == "__main__":
    form = cgi.FieldStorage()
    username_ = form.getvalue('username')
    userhash_ = form.getvalue('userhash')
    account_ = form.getvalue('account')
    try:
        api.output(main(username_, userhash_, account_))
    except CurangelError as e:
        errorHandler.throwError(e.fmt())
