import subprocess, sys, thread, time, os, platform, __builtin__
from os.path import exists, abspath
try:
    import Cocoa # mac
except: pass

from PyQt4 import QtGui, QtCore

import audio as AUDIO
import ini
from constants import *

import gameview, mainmenu, options, demo

__builtin__.audio = AUDIO
del AUDIO

osname = platform.system()

if osname == "Linux": QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) # Linux fix
app = QtGui.QApplication(sys.argv)

path = sys.argv[0]
demofile = None

if len(sys.argv) > 1:
    demofile = sys.argv[-1]
    if not exists(demofile):
        QtGui.QMessageBox.critical(None, "Unable to load demo", "The demo file '%s' doesn't exist." % (demofile))
        os._exit(-2)

if osname == "Darwin":
    path = Cocoa.NSBundle.mainBundle()
    os.chdir(path.resourcePath())

missing = audio.checkAvailable()
if missing:
    QtGui.QMessageBox.critical(None, "Unable to launch game", "Couldn't find the file %s on the client folder.\nAO2XP needs this file in order to play sounds and music.\nThe file is included in the client's zip file, make sure it's in the same folder as the AO2XP exe.\n\nAdditional info:\n%s\n%s" % (missing, sys.argv, os.getcwd()))
    os._exit(-2)

class gamewindow(QtGui.QMainWindow):
    def __init__(self):
        super(gamewindow, self).__init__()
        self.stackwidget = QtGui.QStackedWidget(self)
        
        self.widget = mainmenu.lobby(self, demofile)
        self.gamewidget = gameview.GUI(self)
        self.stackwidget.addWidget(self.widget)
        self.stackwidget.addWidget(self.gamewidget)
        self.setCentralWidget(self.stackwidget)
        self.stackwidget.setCurrentWidget(self.widget)
        self.setFixedSize(self.widget.lobbyimg.size().width(), self.widget.lobbyimg.size().height())
        self.center()
        self.setWindowTitle("AO2XP")
        self.setWindowIcon(QtGui.QIcon("AO2XP.ico"))
        self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)
        
        self.settingsgui = options.Settings(self)
        self.demopickergui = demo.DemoPicker(self)
        self.aboutgui = self.aboutBox()
        
        if demofile:
            self.gamewidget.start_demo(demofile)
            self.stackwidget.setCurrentWidget(self.gamewidget)
    
    def center(self):
        frameGm = self.frameGeometry()
        centerPoint = QtGui.QDesktopWidget().availableGeometry().center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())
    
    def showGame(self, tcp, playerlist, charlist, musiclist, background, evidence, areas, features=[], oocjoin=[], hplist=[], webAO_bucket=""):
        self.gamewidget.disconnectnow = False
        self.gamewidget.start_game(tcp, playerlist, charlist, musiclist, background, evidence, areas, features, oocjoin, hplist, webAO_bucket)
        self.stackwidget.setCurrentWidget(self.gamewidget)
    
    def returnToMenu(self):
        self.gamewidget.disconnectnow = True
        self.setFixedSize(self.widget.lobbyimg.size().width(), self.widget.lobbyimg.size().height())
        self.widget.onClicked_cancelconnect()
        self.stackwidget.setCurrentWidget(self.widget)
        self.setWindowTitle("AO2XP")
        self.center()
    
    def showSettings(self):
        self.settingsgui.showSettings()
        
    def show_demo_picker(self):
        self.demopickergui.show()
        
    def aboutBox(self):
        box = QtGui.QMessageBox()
        box.setText("AO2XP %s\nRunning on %s %s %s (Python %s)\n\n2019-2025 headshot / cidoku" % (GAME_VERSION, platform.system(), platform.release(), platform.machine(), platform.python_version()))
        box.setWindowTitle("About AO2XP")
        box.setStandardButtons(QtGui.QMessageBox.Close)
        box.setWindowIcon(QtGui.QIcon("AO2XP.ico"))
        box.setIconPixmap(QtGui.QPixmap(AO2XPpath + "icons/about.png"))
        box.button(QtGui.QMessageBox.Close).setText('Take that!')
        return box

# Vanilla downloader
force_downloader = len(sys.argv) > 1 and sys.argv[1] == "download"
if force_downloader or (not exists("base/background") and not exists("base/characters") and not exists("base/sounds") and not exists("base/evidence")):
    jm = QtGui.QMessageBox.information(None, "Warning", "You seem to be missing the included Attorney Online content.\nWould you like to download them automatically?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
    if jm == QtGui.QMessageBox.Yes:
        import basedownloader
        code = basedownloader.downloadVanilla()
        if code != 0: os._exit(code)
    else:
        os._exit(-3)

# AO2XP update checker
can_update = ini.read_ini_bool("AO2XP.ini", "General", "install updates", False) # Automatic updates are opt-in!
force_update = "forceupdate" in sys.argv[1:]
if can_update or force_update:
    import updater
    code = updater.checkForUpdates(force_update)
    if code == 0:
        subprocess.Popen(["./AO2XPupdat"])
        os._exit(0)
    elif osname == "Darwin": # bundle
        os.chdir(path.resourcePath()) # return to Resources folder

# This hides stupid useless QT warnings
def handler(msg_type, msg_string):
    pass
QtCore.qInstallMsgHandler(handler)

audio.init()
game = gamewindow()
game.show()
returnc = app.exec_()
audio.free()
sys.exit(returnc)