# 
#  Copyright (C) 2009-2010,2013-2015,2019  Smithsonian Astrophysical Observatory
#
#
#  This program 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 3 of the License, or
#  (at your option) any later version.
#
#  This program 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 this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


from __future__ import print_function
import os
import sys
import IPython.core.interactiveshell
import traceback as _tb_ 

__all__ = ["script", "init"]

# Fix for #14096 CIAO is no longer in the path from within ipython
os.environ["SHELL"]="/bin/sh"

# get the interactive shell
# OL: after upgrading ipython from 1.x to 2.x we ha
_ishell_ = IPython.core.interactiveshell.InteractiveShell.instance()

# create a tracebacklimit member to sys to specify the 
# number of tracebacks displayed with an error 
# initialize to zero for no traceback
if hasattr(sys, "tracebacklimit") is False:
   sys.tracebacklimit = 0 

try:
   import ciao_version as cv
except ImportError:
   import warnings
   warnings.warn("Unable to load the ciao_version module to determine version number- defaulting %s version to 0.0.0"%__name__, Warning)
   __version__ = "0.0.0"
else:
   __version__ = cv.get_ciao_version()

__ciao_app_name__ = ''


def ciao_exception_handler(self, type, value, traceback, tb_offset=None):
    if sys.tracebacklimit and sys.tracebacklimit > 0:
       _tb_.print_tb(traceback, sys.tracebacklimit) 
    if str(value).find('chips ') == 0:
       print('%s' % (value,), file=sys.stderr)
    else:
       print('%s: %s' % (type.__name__, value), file=sys.stderr)
    return _tb_.format_exc()


_ishell_.set_custom_exc((Exception, KeyboardInterrupt), ciao_exception_handler)


def script(filename=None, clobber=False):

   if filename is None:
      filename = __ciao_app_name__.lower ()+".log"
   
   if os.path.isfile(filename) and not clobber:
      raise IOError("script file %s exists and clobber is not set." % filename)

   hist = _ishell_.history_manager.input_hist_parsed
   cmd = _ishell_.find_user_code ('0:{0}'.format (len(hist)-1), False)

   fp = open(filename,"w")

   # remove the last line -- it's a call to the script function
   fp.write(cmd)
   fp.close()

__script_doc_template__ = """
   script

   SYNOPSIS
      Save {0} session commands to file

   SYNTAX

   Arguments:
      filename  - script filename
                  default = '{1}.log'
      clobber   - clobber file flag
                  default = False

   Returns:
      None

   DESCRIPTION
      Save {0} commands from current session to a script file.

   SEE ALSO
      save
"""
script.__doc__ = __script_doc_template__.format(__ciao_app_name__, __ciao_app_name__.lower())


def init (ciao_app_name = ''):
   __ciao_app_name__ = ciao_app_name
   script.__doc__ = __script_doc_template__.format(__ciao_app_name__, __ciao_app_name__.lower())

