'''
Created on 19 maj 2014

@author: Reii
'''

# -*- coding: cp1252 -*-

from Tkinter import *
from ttk import Frame, Button, Style, Entry, Label, Scale
import tkMessageBox as box
import server

class ConnectGUI( Frame ):
  
    def __init__( self, parent, mainGUI ):
        Frame.__init__( self, parent )

        self.mainGUI = mainGUI
        self.parent = parent
        self.maxPlayers = IntVar()
        self.maxPlayers.set( 6 )
        self.roundTimeMin = IntVar()
        self.roundTimeMin.set( 3 )

        self.initUI()

    def initUI(self):

        self.parent.title("Start Server")
        self.style = Style()
        self.style.theme_use("default")

        frame = Frame( self, relief=RAISED, borderwidth=1 )
        frame.pack( fill=BOTH, expand=1 )

        portFrame = Frame( frame )
        portFrame.pack( side=TOP, pady=5 )
        portLabel = Label(portFrame, text="Server Port: ")
        portLabel.pack( side=LEFT)
        self.port = Entry( portFrame, width=10)
        self.port.pack(side=LEFT)

        maxPlayerFrame = Frame( frame )
        maxPlayerFrame.pack( side=TOP, pady=5 )
        maxPlayerText = Label( maxPlayerFrame, text="Max Players: " )
        maxPlayerText.pack( side=LEFT)
        maxPlayer = Scale( maxPlayerFrame, from_=2, to=8, command=self.onPlayerScale )
        maxPlayer.set( self.maxPlayers.get() )
        maxPlayer.pack( side=LEFT )
        maxPlayerLabel = Label( maxPlayerFrame, textvariable = self.maxPlayers )
        maxPlayerLabel.pack( side=LEFT )

        roundTimeFrame = Frame( frame )
        roundTimeFrame.pack( side=TOP, pady=5 )
        roundTimeText = Label(roundTimeFrame, text="Round Time: ")
        roundTimeText.pack( side=LEFT )
        roundTime = Scale( roundTimeFrame, from_=3, to=30, command=self.onTimeScale )
        roundTime.set( self.roundTimeMin.get() )
        roundTime.pack(side=LEFT)
        roundTimeLabel = Label( roundTimeFrame, textvariable = self.roundTimeMin )
        roundTimeLabel.pack( side=LEFT )

        self.pack( fill=BOTH, expand=1 )

        quitButton = Button( self, text="Cancel", command=self.parent.destroy )
        quitButton.pack( side=RIGHT, padx=5 )
        startButton = Button( self, text="Start Server", command=self.start )
        startButton.pack( side=RIGHT, padx=5, pady=5 )

    def onPlayerScale( self, value ):
        self.maxPlayers.set( int( float( value ) ) )

    def onTimeScale( self, value ):
        self.roundTimeMin.set( int( float( value ) ) )

    def start( self ):
        try:
            validatedPort = int( self.port.get() )
            if( validatedPort < 0 and validatedPort > 65535 ):
                box.showerror("Error", "Invalid port number!")
                return
        except:
            box.showerror("Error", "Invalid port number!")
            return
        self.startServer( validatedPort, self.maxPlayers.get(), self.maxPlayers.get() )

    def startServer( self, port, maxPlayers, gameTime ):
        serv = server.Server( port, maxPlayers, gameTime, self.mainGUI )
        self.mainGUI.setServer( serv )
        self.mainGUI.disableStart( )
        self.mainGUI.enableStop()
        serv.openLobby()
        self.parent.destroy()
        
        
class ServerGUI( Frame ):
    
    def __init__( self, parent ):
        Frame.__init__( self, parent )

        parent.protocol( "WM_DELETE_WINDOW", self.closeCallback )
        self.parent = parent
        
        self.server = None
        
        self.initUI( )

    def initUI( self ):
        
        self.parent.title( "Shadowfiend Server 1.0" )
        
        self.menubar = Menu( self.parent )
        self.parent.config( menu=self.menubar )
        
        self.menubar.add_cascade( label="Start Server", command=self.openConnect )
        
        self.quitMenu = Menu( self.menubar )
        self.quitMenu.add_command( label="Stop Server", command=self.stopServer )
        self.quitMenu.add_command( label="Exit Application", command=self.exit )
        self.menubar.add_cascade( label="Exit", menu=self.quitMenu )
        
        self.quitMenu.entryconfig( 1, state="disabled")
        
        logScroll = Scrollbar( self.parent )
        logScroll.pack( side=RIGHT, fill=Y )
        
        self.textLog = Text( self.parent, height=2, width=50 )
        self.textLog.pack( side=LEFT, fill=Y )
        self.textLog.configure( state="disabled")
        
        logScroll.config( command=self.textLog.yview )
        self.textLog.config( yscrollcommand=logScroll.set )
        
        self.listBox = Listbox( self.parent )
        self.listBox.pack( fill=X )
        self.listBox.configure( state="disabled")
    
    def disableStart( self ):
        self.menubar.entryconfig( 1, state="disabled")
        
    def enableStart( self ):
        self.menubar.entryconfig( 1, state="active")
        
    def disableStop( self ):
        self.quitMenu.entryconfig( 1, state="disabled")
        
    def enableStop( self ):
        self.quitMenu.entryconfig( 1, state="active")
    
    def openConnect( self ):
        top = Toplevel()
        top.geometry( "300x130" )
        top.resizable( width=FALSE, height=FALSE )
        top.title( "Start Server" )
        ConnectGUI( top, self )
        
    def addPlayer( self, name, address ):
        self.listBox.configure( state="active")
        self.listbox.insert( END, name + " : " + address )
        self.listBox.configure( state="disabled")
    
    def removePlayer( self, name ):
        for entry, pos in self.listBox:
            if name in entry:
                self.listBox.configure( state="active")
                self.listbox.delete( pos )
                self.listBox.configure( state="disabled")
    
    def exit( self ):
        self.stopServer()
        self.parent.destroy()
    
    def stopServer( self ):
        if self.server != None:
            self.server.running = False
            self.server.socket.close()
            self.enableStart()
            self.disableStop()
    
    def setServer( self, serv ):
        self.server = serv

    def closeCallback( self ):
        if box.askokcancel("Quit", "Do you really wish to exit?"):
            self.exit()

def main():

    root = Tk()
    root.geometry( "600x480" )
    root.resizable( width=FALSE, height=FALSE )
    ServerGUI( root )
    root.mainloop()  


if __name__ == '__main__':
    main()  