# Module for recurring events and world updates

import time,sched
from util import *

sc = sched.scheduler(time.time,time.sleep)
adde = sc.enter

def init():
    # setup hourly update, starting at the next hour
    t = list(time.localtime())
    t[4] = t[5] = 0; t[3] += 1
    sc.enterabs(time.mktime(t),1,hup,())
    sc.enter(15,9,sup,())

# hourly update
def hup():
    import core
    for a in core.Thing.all:
        if is_a(a,core.Actor):
            a.sendl("{YYou receive your hourly stipend of {g${x20{Y.{x")
            a.cash += 20

    for r in core.Thing.all:
        e = 0  # expenses
        i = 0  # income
        if r.shop: e = r.shop.restock(); i += r.shop.rev; r.shop.rev = 0

        if is_a(r,core.Room):
            e += r.biz.rent  # expenses

            for p in cplayers():
                if p.name == r.biz.owner:
                    p.cash += i - e
                    p.sendl("{rYou pay {g${r%d in rent and expenses.{x" % e)
                    p.sendl("{YYou get {g${Y%d in sales revenue." % i)

    adde(3600,1,hup,()) # reschedule

# fighting update
def fup(p):
    foe = p.foe
    if not foe: return
    p.ks = randint(1,2)
    p.sendl("{G>> You are ready to attack or insult {g%d{G time%s.{x" % (p.ks, p.ks > 1 and "s" or ""))
    adde(10,1,fup,(p,))

    if p.npc: # handle npc fighting
        # really dumb at the moment
        # it'd be cool to have an insult generator here
        for x in xrange(p.ks):
            # schedule reaction
            adde(x+1,3,p.do,[choice(["slap","pat","laugh","scold"])])

# ambient crowd response during a fight
def fam(*ps):
    p1,p2 = ps
    if p1.foe != p2: return

    bs = p1.room.crowd  # bystanders -- well, not always (bug)

    if len(bs) > 1:
        b = choice(bs)
        r = randint(0,2)
        if r == 1: Act(b).all('The crowd chants, "{RFIGHT! FIGHT! FIGHT!{x"')
        if r == 2 and b not in ps: b.do("say You both suck!")

    adde(15,3,fam,ps)

# travel update for NPCs
def tup(S):
    if S.path:
        if not S.foe: S.go(S.path.pop())
        adde(3,4,tup,[S])

# spawn random flavor samples
def sup():
    import core,world
    rs = [r for r in core.Thing.all if is_a(r,core.Room)]
    s = core.Sample()
    s.fl = choice(["peach","strawberry","chocolate","cinnamon"])
    s.name = "a "+s.fl
    s.goto(choice(rs))

# NPC update
def nup(S):
    import world
    if S.path: return
    else:
        for x in S.inv:
            if is_a(x,world.Drink):
                x.on_drink(S); adde(randint(60,95),9,nup,[S]); return

    adde(randint(15,30),9,nup,[S])

    if randint(0,9) < 2: return

    ranks = S.rankall()

    if not ranks: return
    for k,r,s,z in ranks:  # rank, room, shop, item data
        if z not in s.inv or not z[1]: continue # skip unavailable
        if r == S.room:
            if not S.buy(s,z): continue
        else: S.travel(r); S.do("say I'm going to %s to buy %s." % (r.name,z[0].name))
        return
    else: # wander
        S.flee()