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

import time
import pygame
from pygame.locals import *
import ConfigParser

from twisted.internet import reactor

import global_vars as g
from resourcemanager import ResourceManager

from gamelogic import *
from graphics import *
from sound import SoundEngine
from gui.gui import *
from menu.menulogin import menuLogin
from menu.menuregister import menuRegister
from menu.menuchar import menuCharacters
from menu.menunewchar import menuNewCharacter
from objects import *
from network.client import *
from network.database import *


class Engine:
    def __init__(self):
        self.FRAMES_PER_SECOND = 20

        # menus
        self.menuLogin = menuLogin(g.screenSurface)
        self.menuRegister = menuRegister(g.screenSurface)
        self.menuChar = menuCharacters(g.screenSurface)
        self.menuNewChar = menuNewCharacter(g.screenSurface)

        self.graphicsEngine = GraphicsEngine()

        self.tmr25 = 0
        self.tmr1000 = 0
        self.walkTimer = 0
        self.clockTick = 0

    def init(self):
        ResourceManager.loadEverything()
        g.soundEngine = SoundEngine()
        g.soundEngine.loadSounds()

        self.initConfig(g.dataPath + '/config.cfg')

        self.setState(MENU_LOGIN)

        pygame.display.flip()
        self.gameLoop()
        reactor.run()

    def initConnection(self):
        ''' starts the connection to the server '''
        connectionProtocol = startConnection()
        g.tcpConn = TCPConnection(connectionProtocol)

    def initConfig(self, configFile):
        ''' reads the configuration file '''

        if not os.path.isfile(configFile):
            print 'No configuration file was found'
            return

        config = ConfigParser.RawConfigParser()
        config.read(configFile)

        try:
            if config.getboolean('sound', 'sfx') is False:
                g.soundEngine.sfxMuted = True

            if config.getboolean('sound', 'music') is False:
                g.soundEngine.musicMuted = True
        except:
            print 'An error occured while reading the configuration file'

    def disconnect(self):
        g.connector.disconnect()

    def setState(self, state):
        ''' sets the game state '''
        if state == MENU_LOGIN:
            g.gameState = MENU_LOGIN
            g.soundEngine.play(SOUND_OPENING, True, True)

        elif state == MENU_REGISTER:
            g.gameState = MENU_REGISTER

        elif state == MENU_CHAR:
            g.gameState = MENU_CHAR

        elif state == MENU_NEWCHAR:
            g.gameState = MENU_NEWCHAR

        elif state == MENU_INGAME:
            g.gameState = MENU_INGAME
            g.soundEngine.play(SOUND_TOWN, True, True)

    def gameLoop(self, FPS=25):
        ''' the main loop of the game '''
        # TODO: DIRTY AREAS
        if g.gameState == MENU_LOGIN:
            self.menuLogin.draw()

        elif g.gameState == MENU_REGISTER:
            self.menuRegister.draw()

        elif g.gameState == MENU_CHAR:
            self.menuChar.draw()

        elif g.gameState == MENU_NEWCHAR:
            self.menuNewChar.draw()

        elif g.gameState == MENU_INGAME:
            # todo: dirty areas

            if g.inGame:
                self.clockTick = time.time() * 1000 # convert to ms

                if self.tmr25 < self.clockTick:
                    self.checkInputKeys()