#! /usr/bin/env python
# -*- coding: UTF-8 -*-
'''
================================================================================
Project: SiriL-ic ( SiriL Image Companion )

This script structures the SiriL work folder into a subfolder, copies the
astronomical images into the subfolders, and builds the associated SiriL
script. It can also group scripts.
================================================================================
   Author:  M27trognondepomme <pebe92 (at) gmail.com>

This program is provided without any guarantee.

The license is  LGPL-v3
For details, see GNU General Public License, version 3 or later.
                       "https://www.gnu.org/licenses/gpl.html"
================================================================================
'''

import wx
import os
import sys

# ------------------------------------------------------------------------------
# Check Mode Developement - Sirilic package is not installed
IsPyInstallerBundle = getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS')
SirilicExist = "sirilic" in sys.modules
if not SirilicExist and not IsPyInstallerBundle:
    from pathlib import Path
    file = Path(__file__).resolve()
    try:
        sys.path.remove(str(file.parent))
    except ValueError:  # Already removed
        pass
    sys.path.append(str(file.parents[1]))
    print("Info: Mode Developement - Sirilic package is not installed")
# ------------------------------------------------------------------------------

from sirilic.lib import tools, callbacks, database, prefs
from sirilic.ui import gui

# ==============================================================================


class App(wx.App):
    def OnInit(self):
        # Configuration
        varname = 'USERPROFILE' if os.name == 'nt' else 'HOME'
        myhome = os.environ.get(varname)
        i_prefs = prefs.CPrefs(myhome, '.sirilic2_rc')
        i_db = database.CDatabase()
        i_gui = gui.CGui(None, -1, "")  # instance Sirilic GUI
        callbacks.CCallbacks(i_gui, i_db, i_prefs)

        # add icon
        iconname = os.path.join(".", "icon", "cp-nb.ico")
        iconpath = os.path.dirname(os.path.abspath(__file__))
        iconfullname = tools.resource_path(iconname, pathabs=iconpath)
        bitmap = wx.Bitmap(iconfullname, wx.BITMAP_TYPE_ICO)
        _icon = wx.NullIcon
        _icon.CopyFromBitmap(bitmap)
        i_gui.SetIcon(_icon)

        # ----------------------------------------------------------------------
        # verification que la taille ne deborde pas de l'ecran
        pos = i_gui.GetPosition()

        # Recherche l'ecran ou va s'afficheer l'interface
        for iScreen in range(wx.Display.GetCount()):
            (x0, y0, width_screen, height_screen) = wx.Display(
                iScreen).GetClientArea().Get()
            if (pos.x >= x0 and pos.y >= y0 and pos.x < x0 + width_screen and pos.y < y0 + height_screen):
                break

        # Taille minimale voulue
        applisize_init = [1360, 1024]
        if sys.platform.startswith('win32'):
            applisize_init = [1150, 925]

        # calcul la taille reelle
        applisize = [0, 0]
        applisize[0] = min(applisize_init[0], width_screen)
        applisize[1] = min(applisize_init[1], height_screen)
        # repositionnement en x si necessaire
        if applisize[0] != applisize_init[0]:
            pos.x = x0
            i_gui.SetPosition(pos)
        # repositionnement en y si necessaire
        if applisize[1] != applisize_init[1]:
            pos.y = y0
            i_gui.SetPosition(pos)

        i_gui.SetSize(applisize)

        # affiche l'interface
        i_gui.Show(True)
        self.SetTopWindow(i_gui)

        return True

# -----------------------------------------------------------------------------


def Run():
    if sys.version_info[0] != 3:
        print("*")
        print("* Python version :", sys.version_info)
        print("* Error, python version should be >= 3 ")
        print("*")
        exit()
    app = App(0)
    app.MainLoop()


if __name__ == '__main__':
    Run()
