# -*- coding: utf-8 -*-
# cython: profile=False

#  Copyright © 2017  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

# pylint: disable=C0326,W0614
# although this file is compiled with Python3 syntax, Cython needs at least division from __future__
from __future__ import print_function, division

# This line makes cython happy
global __name__, __package__
#px/__compiled = True
__compiled = False

import sys

from pybiklib import config as config_

#px+from qt cimport *
#px/cimport qt as Qt
from .debug_purepython import *

#px/from libc.stdio cimport printf
def printf(fmt, *args): print(fmt % args, end='')
#px/from libc.stdio cimport puts
puts = print

#px/cdef enum: #
if True:
    DEBUG_MSG = 0x0002
    DEBUG_MSGEXT = 0x0020
#px+cdef long debug
debug = 0
    
def set_debug_flags(module):
    global debug
    if module.DEBUG_MSG:   debug |= DEBUG_MSG
    if module.DEBUG_MSGEXT: debug |= DEBUG_MSGEXT
    

#### Helpers (same as in module qt) ####

#pxm-FUNC P
def q2str(qstr:str)->'':  return qstr
    #px+cdef QByteArray data = qstr.toUtf8()
    #px+return data.data()[:data.size()].decode('utf-8')
#pxm-FUNC P
def str2q(pstr)->str:  return pstr
    #px+data = pstr.encode('utf-8')
    #px+return fromUtf8(<char*>data, len(data))
    

#### . ####

def get_gl_variant():
    #px+cdef int i
    # This function requires that the app instance is already created
    i = openGLModuleType()
    if i == LibGL:
        return 'ogl'
    elif i == LibGLES:
        return 'es2'
    else:
        print('Unknown openGLModuleType', i)
        return ''
        
def exec_application(main):
    #px-
    global app #http://pyqt.sourceforge.net/Docs/PyQt5/gotchas.html#crashes-on-exit
    
    #setAttribute(Qt.AA_X11InitThreads)
    #setAttribute(Qt.AA_UseDesktopOpenGL)
    #setAttribute(Qt.AA_UseSoftwareOpenGL)
    
    #px+try:
    #px+    byteslist = [arg.encode(sys.getdefaultencoding()) for arg in main.opts.ui_args]
    #px+except Exception:
    #px+    sys.excepthook(*sys.exc_info())
    #px+    byteslist = []
    #px+args_buffer = b'\0'.join(byteslist) + b'\0'
    #px+
    #px+ptr = int(<size_t><void*><char*>args_buffer)
    #px+ptrlist = []
    #px+for arg in byteslist:
    #px+    ptrlist.append(ptr)
    #px+    ptr += len(arg)+1
    #px+ptrlist.append(0)
    #px+
    #px+import struct
    #px+argv_buffer = struct.pack('{}P'.format(len(ptrlist)), *ptrlist)
    #px+cdef int argc = len(byteslist)
    #px+cdef char **argv = <char**><void*><char*>argv_buffer
    #px/cdef QApplication *app = new QApplication(argc, argv)
    app = QApplication(main.opts.ui_args)
    
    qargs = app.arguments()
    #px/if qargs.size() > 1:
    if len(qargs) > 1:
        print('Unknown arguments:')
        #px/for i in range(1, qargs.size()):
        for i in range(1, len(qargs)):
            print(' ', q2str(qargs[i]))
        return 1
    
    app.setOrganizationName(str2q(config_.PACKAGE))
    app.setApplicationName(str2q(config_.APPNAME))
    app.setApplicationVersion(str2q(config_.VERSION))
    app.setWindowIcon(QIcon(str2q(config_.APPICON_FILE)))
    
    # initialize translation
    language = q2str(QLocale_system().name())
    # standard Qt translation, used for e.g. standard buttons and shortcut names
    # keep the translator object for the lifetime of the app object, so that the translation works
    #px/cdef QTranslator translator
    translator = QTranslator()
    translator.load(str2q("qt_" + language), location(TranslationsPath))
    #px/app.installTranslator(&translator)
    app.installTranslator(translator)
    main.cb_app_post_create(language)
    
    #XXX: needed for threaded rendering, prevents blocking on quit
    #px/connect(app, &aboutToQuit, app, &sync, Qt.DirectConnection)
    app.aboutToQuit.connect(app.sync, type=Qt.DirectConnection)
    
    while True:
        pyapp = main.cb_run_app()
        if pyapp is None:
            break
        pyapp.cb_before_mainloop()
        app.exec()
        pyapp.cb_after_mainloop()
    del app
    
#px+depends = [[DEPENDS]]
#px+aliases = [[ALIASES]]


