 #!/usr/bin/env python

import os, pygame, ode, time
from random import randint, choice
from pygame.locals import *
from functions import CollisionCallback,combo,drawText
from messagebox import *
from fist import *
from enemy import *
from blood import *
from options import *
#from fileops import *

if not pygame.font: print 'Warning! Fonts unavailable!'
if not pygame.mixer: print 'Warning! Sound unavailable!'
            
def kulaPunch(odebody,target):
    pos = odebody.getPosition()
    hitbox = Rect(pos[0],pos[1],20,20)
    return hitbox.colliderect(target.rect)
        

def startGame():
#Initialize Everything
    opcje = Options()
    opcje.loadFromXML("options.xml")
    #MessageBox("Start!","Start game?")
    #pygame.init()
    #width, height = 800, 600
    width, height = 1024, 768
    screen = pygame.display.set_mode((width, height),FULLSCREEN|HWSURFACE|DOUBLEBUF)
    #screen = pygame.display.set_mode((width, height),FULLSCREEN)
    pygame.display.set_caption('Kimboot')
    pygame.mouse.set_visible(0)
    
    world = ode.World()
    world.setERP(0.8)
    world.setCFM(1E-5)
    space=ode.Space()
    contactgroup=ode.JointGroup()
#    world.setGravity((0,-9.81,0))
    
    body1 = ode.Body(world)
    M = ode.Mass()
    M.setSphere(1500, 0.05)
    body1.setMass(M)
    tup = pygame.mouse.get_pos()
    x,y = tup[0],tup[1]
    pozycja = []
    pozycja.extend((float(x),float(y),0.0))
    print pozycja
    body1.setPosition(pozycja)
    rope = [body1]
    ropejoints = []
    ogniwa = 10
    val = 210
    for i in range(1,ogniwa):
        rope.append(ode.Body(world))
        M = ode.Mass()
        M.setSphere(500, 0.05)
        rope[i].setMass(M)
        rope[i].setPosition((pozycja[0]+(i*(val/ogniwa)),pozycja[1]+(i*(val/ogniwa)),0))
        ropejoints.append(ode.BallJoint(world))
        ropejoints[i-1].attach(rope[i-1], rope[i])
        ropejoints[i-1].setAnchor(rope[i-1].getPosition())
    ballbody = ode.Body(world)
    M = ode.Mass()
    M.setSphere(2500, 0.05)
    ballbody.setMass(M)
    ballbody.setPosition((pozycja[0]+((i+1)*(val/ogniwa)),pozycja[1]+((i+1)*(val/ogniwa)),0))
    radius = 30
    geom2=ode.GeomSphere(space,radius)
    geom2.setBody(ballbody)
    geom2.size=radius
    
    j2 = ode.BallJoint(world)
    j2.attach(rope[-1], ballbody)
    j2.setAnchor(rope[-1].getPosition())
#    j2.setAnchor( (1,2,0) )

    tlo = pygame.Surface(screen.get_size(),HWSURFACE|DOUBLEBUF)
    tlo = tlo.convert()
    tlo.fill((250, 250, 250))
    wygaszenie = pygame.Surface(screen.get_size(),HWSURFACE|DOUBLEBUF)
    wygaszenie.fill((250,250,250))
    wygaszenie.set_alpha(100)
    
    screen.blit(tlo, (0, 0))
    pygame.display.flip()
    
    clock = pygame.time.Clock()
    aww_sound = load_sound('aww.wav',opcje)
    punch_sound = load_sound('punch.wav',opcje)
    screams, splats, bravos = [], [], []
    for i in range(5):
        screams.append(load_sound("scream0"+str(i+1)+".wav",opcje))
    for i in range(6):
        splats.append(load_sound("splat0"+str(i+1)+".wav",opcje))
    for i in range(5):
        bravos.append(load_sound("bravo0"+str(i+1)+".wav",opcje))
    enemies = []
    for i in range(2):
        enemies.append(Enemy(world,space,width,height))
    fist = Fist(world,space)
    ball = pygame.sprite.Sprite()
    ball.image, ball.rect = load_image('ball.png', -1)
    ball.body = ballbody
    allsprites = pygame.sprite.RenderPlain((fist, enemies, ball))
    corpses = pygame.sprite.RenderPlain()
    
    fps = 50
    dt = 1.0/fps
    loopFlag = True
    clk = pygame.time.Clock()
    ticks = 0
    czestosc = 90
    kombo = False
    komboile = 0
    czaskomba = 0
    napis,napispos = wypisz("",(200,10,10),(250,250,250),tlo,200)
    startnapisu = 0
    punkty, trupy, najkombo = 0, 0, 0
    krew = Blood(opcje)
    #for drop in krew.particles:
    #    krewy.add(drop)
    jest_krew = False
    
    while 1:
        clock.tick(60)
        
        if (ticks % czestosc == 0):
            enemies.append(Enemy(world,space,width,height))
            allsprites.add(enemies[-1])
        if (ticks % 1000 == 0):
            if (czestosc > 20):
                czestosc -= 20
            ticks = 0
        if (startnapisu>0 and time.time()-startnapisu>2):
            kasujNapis(napis,napispos,tlo)

        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == MOUSEBUTTONDOWN:
                if event.button > 1:
                    return
            elif event.type == MOUSEBUTTONUP:
                fist.unpunch()
                
        (x,y) = pygame.mouse.get_pos()
        roznica = height-60-y
        if (roznica<0):
            pygame.mouse.set_pos(x,y+roznica)
        if (roznica>height-120):
            pygame.mouse.set_pos(x,y+(roznica-height+120))
                
        for en in enemies:
            if kulaPunch(ballbody,en):
                #~ en.die()
                choice(screams).play()
                choice(splats).play()
                tempvel = ball.body.getLinearVel()
                velx = tempvel[0]/opcje["BloodSpread"]
                vely = tempvel[1]/opcje["BloodSpread"]
                krew.spawn((en.rect.center[0],en.rect.center[1]),(velx,vely))
                jest_krew = True
                #en.punched()
                punkty += 1
                trupy += 1
                wypisz("Kills: "+str(trupy),(10,10,10),(250,250,250),tlo,-400)
                wypisz("Points: "+str(punkty),(10,10,10),(250,250,250),tlo,-200)
                tlo.blit(Corpse(en.rect.topleft[0],en.rect.topleft[1]).image,(en.rect.topleft[0],en.rect.topleft[1]))
                rog = randint(1,4)
                if rog == 1:
                    en.rect.topleft = 10, 10+50
                elif rog == 2:
                    en.rect.topleft = width-70, 10+50
                elif rog == 3:
                    en.rect.topleft = width-70, height-70
                else:
                    en.rect.topleft = 10, height-70
                enemies.remove(en)
                allsprites.remove(en)
                kombo = True
                komboile += 1
                czaskomba = time.time()
            elif (kombo == True and (time.time() - czaskomba) > 0.5):
                kombo = False
                if komboile > 1:
                    stor = "Kombo x"+str(komboile)+"!"
                    napis,napispos = wypisz(stor,(200,10,10),(250,250,250),tlo,50)
                    startnapisu = time.time()
                    punkty += combo(komboile)-komboile
                    choice(bravos).play()
                    wypisz("Points: "+str(punkty),(10,10,10),(250,250,250),tlo,-200)
                if komboile > najkombo:
                    najkombo = komboile
                    stor = "Max kombo: x"+str(najkombo)
                    wypisz(stor,(10,10,10),(250,250,250),tlo,300)
                komboile = 0
            #if kulaPunch(fist.body,en):
            if fist.Check(en):
                aww_sound.play()
                #drawText("Points: "+str(punkty)+", kills: "+str(trupy)+", max kombo: x"+str(najkombo),(0,0,0),(255,255,255),(400,400))
#                MessageBox2("Points: "+str(punkty)+", kills: "+str(trupy)+", max kombo: x"+str(najkombo),tlo)
                wynik = (punkty,trupy,najkombo)
                punkty = 0
                return wynik

        allsprites.update()
        if (jest_krew):
            krew.update(tlo)
        if (len(krew.particles)<1 and jest_krew == True):
            jest_krew = False
            tlo.blit(wygaszenie,(0,0))
        
        #screen.fill((250,250,250))
        #tlo.set_alpha(150)
        screen.blit(tlo, (0, 0))
        #screen.blit(wygaszenie,(0,0))
        allsprites.draw(screen)
        
        pozycja = list(pygame.mouse.get_pos())
        pozycja.append(0)
        body1.setPosition(pozycja)
        tmp = [pozycja[0]+fist.radius,pozycja[1]+fist.radius,0]
        fist.body.setPosition(tmp)
        fist.geom.setPosition(tmp)
        x1,y1,z1 = body1.getPosition()
        x2,y2,z2 = ballbody.getPosition()
        ball.rect.midtop = x2,y2-20
        #pygame.draw.circle(screen, (0,0,0), (x2,y2), 20, 0)
        for i in range(len(rope)-1):
            a1,b1,c1 = rope[i].getPosition()            
            a2,b2,c2 = rope[i+1].getPosition()
            pygame.draw.line(screen, (55,0,200), (a1,b1), (a2,b2), 2)
        pygame.draw.line(screen, (55,0,200), (a2,b2), (x2,y2), 2)
        pygame.display.flip()
        
        space.collide((world,contactgroup),CollisionCallback)
        fist.saveZPos(ballbody)
        
        world.step(dt)
        fist.loadZPos(ballbody)
        contactgroup.empty()
 
        clk.tick(fps)
        ticks += 1


if __name__ == '__main__': startGame()