# # !/home/linuxero/proj/tero/pyqcrm/.qtcreator/venv-3.13.1/bin/python3
import os
import sys
# noinspection PyUnresolvedReferences
import rc_pyqcrm
# noinspection PyUnresolvedReferences
import rc_qml

from PySide6.QtCore import QIODevice
from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtWidgets import QSystemTrayIcon

from lib.ConfigLoader import ConfigLoader
from lib.DB.AddressModel import AddressModel
from lib.DB.ApplicantModel import ApplicantModel
from lib.DB.BTypeModel import BTypeModel
from lib.DB.BusinessModel import BusinessModel
from lib.DB.ContactModel import ContactModel
from lib.DB.EmployeeModel import EmployeeModel
from lib.DB.ObjectModel import ObjectModel
from lib.DB.UserManager import UserManager
from lib.Printers import Printers
from lib.domain.BaseModel import database

os.environ['QML_XHR_ALLOW_FILE_READ'] = '1'

bad_config = False
db_con = False
address_model = None
applicant_model = None
business_model = None
business_type = None
contact_model = None
employee_model = None
object_model = None
printers = None
user = None


def initializeProgram():
    global address_model, applicant_model, bad_config, business_model, user, business_type, contact_model, employee_model, object_model, db_con, printers
    if not bad_config:
        dbconf = config.getConfig()['database']
        database.init(
            host=dbconf['DB_HOST'],
            user=dbconf['DB_USER'],
            password=dbconf['DB_PASS'],
            database=dbconf['DB_NAME'],
            port=int(dbconf['DB_PORT']),
            connect_timeout=5,
        )
        database.connect()

        printers = Printers()
        if not database.is_closed():
            db_con = True
            user = UserManager()
            business_model = BusinessModel()
            address_model = AddressModel()
            applicant_model = ApplicantModel()
            business_type = BTypeModel()
            contact_model = ContactModel()
            employee_model = EmployeeModel()
            object_model = ObjectModel()
            publishContext()


def configReady():
    global bad_config
    bad_config = False
    initializeProgram()


def publishContext():
    global engine, address_model, applicant_model, bad_config, business_model, user, business_type, contact_model, object_model, employee_model, printers
    engine.rootContext().setContextProperty("loggedin_user", user)
    engine.rootContext().setContextProperty("business_model", business_model)
    engine.rootContext().setContextProperty("address_model", address_model)
    engine.rootContext().setContextProperty("applicantModel", applicant_model)
    engine.rootContext().setContextProperty("business_type", business_type)
    engine.rootContext().setContextProperty("contact_model", contact_model)
    engine.rootContext().setContextProperty("employee_model", employee_model)
    engine.rootContext().setContextProperty("object_model", object_model)


if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    pyq_sok = QLocalSocket()
    pyq_sok.connectToServer("PYQCRM_INSTANCE", QIODevice.ReadOnly)

    if pyq_sok.state() == QLocalSocket.ConnectedState:
        print("PYQCRM already running..")
        print("Stop the running instance before running the application..")
        sys.exit(-1)
    else:
        print("Starting PYQCRM_INSTANCE")
        pyq_server = QLocalServer()
        pyq_server.listen("PYQCRM_INSTANCE")

    engine.addImportPath("qrc:/")

    qml_file = "qrc:/Gui/main.qml"

    icon = QIcon("qrc:/images/tero.jpg")
    app.setWindowIcon(icon)

    tray = QSystemTrayIcon()
    tray.setIcon(icon)
    tray.setToolTip("PYQCRM")

    config = ConfigLoader()

    if not config.getConfig():
        bad_config = True
        config.configurationReady.connect(configReady)
    else:
        initializeProgram()

    engine.rootContext().setContextProperty("config", config)
    engine.rootContext().setContextProperty("sys_printers", printers)
    engine.rootContext().setContextProperty("bad_config", bad_config)
    engine.rootContext().setContextProperty("db_con", db_con)
    engine.rootContext().setContextProperty("systray", tray)

    engine.load(qml_file)

    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec())
