#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Application entry point."""

# Standard library imports
import sys

# Third party imports
from qtpy.QtCore import QEvent, QObject, Qt

# Local imports
from anaconda_navigator.static.fonts import load_fonts
from anaconda_navigator.utils.qthelpers import qapplication
from anaconda_navigator.widgets.dialogs.splash import SplashScreen
from anaconda_navigator.widgets.main_window import MainWindow

MAC = sys.platform == 'darwin'


def run_app(splash):
    """Create and show Navigator's main window."""
    window = MainWindow(splash=splash)
    window.setup()
    return window


class EventEater(QObject):
    """Event filter for application state."""

    def __init__(self, app):
        """Event filter for application state."""
        super(EventEater, self).__init__()
        self.app = app

    def eventFilter(self, ob, event):
        """Qt override."""
        if event.type() == QEvent.ApplicationActivate and MAC:
            self.app.window.show()
            if self.app.window.isMaximized():
                self.app.window.showMaximized()
            else:
                self.app.window.showNormal()
        return False


def main():  # pragma: no cover
    """Main application entry point."""
    global app
    app = qapplication(test_time=60)

    # For retina displays on qt5
    if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
        app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    event_eater = EventEater(app)
    load_fonts(app)
    splash = SplashScreen()
    splash.show_message("Initializing...")
    window = run_app(splash)
    app.window = window
    app.installEventFilter(event_eater)
    app.exec_()


if __name__ == '__main__':  # pragma: no cover
    main()
