# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals

import importlib
import os

PYSIDE = None
is_py6 = False


def _import_binding(binding_name):
    module = importlib.import_module(binding_name)
    QtCore = module.QtCore
    QtGui = module.QtGui
    QtWidgets = module.QtWidgets
    Qt = QtCore.Qt
    return QtCore, QtGui, QtWidgets, Qt


def _load_qt():
    force = os.environ.get("NCA_FORCE_PYSIDE", "").strip()
    candidates = []

    if force == "2":
        candidates = ["PySide2", "PySide6"]
    elif force == "6":
        candidates = ["PySide6", "PySide2"]
    else:
        candidates = ["PySide2", "PySide6"]

    last_error = None
    for binding_name in candidates:
        try:
            QtCore, QtGui, QtWidgets, Qt = _import_binding(binding_name)
            return binding_name, (binding_name == "PySide6"), QtCore, QtGui, QtWidgets, Qt
        except Exception as exc:
            last_error = exc

    raise ImportError(
        "Unable to import any supported Qt binding. "
        "Tried: {0}. Last error: {1!r}".format(", ".join(candidates), last_error)
    )


PYSIDE, is_py6, QtCore, QtGui, QtWidgets, Qt = _load_qt()

try:
    QAction = QtWidgets.QAction
except AttributeError:
    QAction = QtGui.QAction

Signal = QtCore.Signal
Slot = QtCore.Slot
Property = QtCore.Property


def exec_dialog(dialog):
    fn = getattr(dialog, "exec", None) or getattr(dialog, "exec_", None)
    if fn is None:
        raise AttributeError("Dialog object has neither exec nor exec_")
    return fn()
