#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2007 Francisco Javier de la Peña
# Copyright © 2010 Francisco Javier de la Peña & Stefano Mazzucco
# Copyright © 2011 Francisco Javier de la Peña, Stefano Mazzucco & Michael Sarahan
#
# This file is part of Hyperspy.
#
# Hyperspy 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 2 of the License, or
# (at your option) any later version.
#
# Hyperspy 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 Hyperspy; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
# USA
import sys

# Deprecate this script
carryon = input("\nStarting HyperSpy using this script is deprecated "
      "and will be removed in HyperSpy 0.9. "
      "Read the HyperSpy online documentation for details.\n"
      "Continue yes/No?")
if carryon not in ["yes", "Yes", "YES"]:
    sys.exit()
    
import os
import shutil
from distutils.version import LooseVersion
try:
    import argparse             # new in Python 2.7
    argp = True
except ImportError:
    argp = False
    import optparse


import IPython

import hyperspy
import hyperspy.Release
import hyperspy.defaults_parser
from hyperspy.defaults_parser import preferences, file_version
from IPython.terminal.ipapp import launch_new_instance


# First we split the argv items in two: the firsts for hyperspy,
# the rest for ipython
ipy_argv = [sys.argv[0], ]
if '--ipython_args' in sys.argv:
    ipy_argv += sys.argv[sys.argv.index('--ipython_args') + 1:]
    sys.argv = sys.argv[:sys.argv.index('--ipython_args')]

hyperspy_module_path = os.path.dirname(hyperspy.__file__)
ipy_hspy = os.path.join(hyperspy_module_path, 'ipython_profile')
ipy_version = LooseVersion(IPython.__version__)

ipython_environments = ['terminal', 'console', 'qtconsole', 'notebook']

ipy_dir = IPython.utils.path.get_ipython_dir()
destination = os.path.join(ipy_dir, 'profile_hyperspy')
# The ipy_dir may not exist if it is the first time that the user
# runs ipython, therefore we must create it, what is done
# automatically when creating a profile
if not os.path.isdir(ipy_dir) or not os.path.isdir(destination):
    # Use the IPython routines to create the directory and profile
    import IPython.core.profileapp
    ipy_create_profile = IPython.core.profileapp.ProfileCreate()
    ipy_create_profile.parse_command_line(['hyperspy', ])
    ipy_create_profile.init_config_files()
    sys.argv.append('--overwrite_profile')

if argp is True:
    parser = argparse.ArgumentParser(
        add_help=True,
        version=hyperspy.Release.version,
        description=hyperspy.Release.description)
else:
    parser = optparse.OptionParser(
        version=hyperspy.Release.version,
        description=hyperspy.Release.description)
parser.add_argument('environment',
                    nargs='?',
                    choices=ipython_environments,
                    default='terminal',
                    help=(
                        'Selects the IPython environment in '
                        'which to start Hyperspy. The default is terminal'))
parser.add_argument('--overwrite_profile',
                    action="store_true",
                    default=False,
                    help=(
                        'Overwrite the Ipython profile with the default one.'))
parser.add_argument('--ipython_args',
                    nargs='*',
                    help=(
                        'Arguments to be passed to IPython. '
                        'This option must be the last one.'
                        'Look at the IPython documentation '
                        'for available options.'))

if argp is True:
    args = parser.parse_args()
else:
    options, args = parser.parse_args()

ipy_config_hspy = os.path.join(ipy_hspy, 'ipython_config.py')
ipy_config_home = os.path.join(destination, 'ipython_config.py')
if not os.path.isfile(ipy_config_home) or \
        args.overwrite_profile or (
        LooseVersion(file_version(ipy_config_hspy)) >
        LooseVersion(file_version(ipy_config_home))):
    shutil.copy(ipy_config_hspy, destination)

additional_dest = os.path.join(destination, 'startup')
if not os.path.isdir(additional_dest):
    os.makedirs(additional_dest)
if not os.path.isfile(os.path.join(additional_dest, 'hyperspy_magics_importer.py')) or \
        args.overwrite_profile:
    shutil.copy(os.path.join(ipy_hspy, 'hyperspy_magics_importer.py'), additional_dest)

# Now that the hspy arguments are parsed, we can delete them from
# sys.argv
sys.argv = ipy_argv


# Add the subcommand first
if args.environment != 'terminal':
    sys.argv.insert(1, args.environment)
sys.argv.append('--profile=hyperspy')
sys.exit(launch_new_instance())
