#_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2010)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
import os
import logging
import numpy
from itertools import izip
import sherpa.ui.utils
from sherpa.ui.utils import _check_type, _send_to_pager
from sh
erpa.utils import SherpaInt, SherpaFloat, sa
o_arange
from sherpa.utils.err import *
from sherpa.data import Data1D
import sherpa.astro.all
import sherpa.astro.plot

warning = logging.getLogger(__name__).warning
info = logging.getLogger(__name__).info



__all__ = ('Session',)


class Session(sherpa.ui.utils.Session):


    ###########################################################################
    # Standard methods
    ###########################################################################


    def __init__(self):
        self._pileup_models     = {}
        self._background_models = {}
        self._background_sources = {}

        self._astrosourceplot= sherpa.astro.plot.SourcePlot()
        self._astrocompsrcplot = sherpa.astro.plot.ComponentSourcePlot()
        self._astrocompmdlplot = sherpa.astro.plot.ComponentModelPlot()
        self._modelhisto = sherpa.astro.plot.ModelHistogram()
        self._bkgmodelhisto = sherpa.astro.plot.BkgModelHistogram()

        self._bkgdataplot = sherpa.astro.plot.BkgDataPlot()
        self._bkgmodelplot = sherpa.astro.plot.BkgModelPlot()
        self._bkgfitplot = sherpa.astro.plot.BkgFitPlot()
        self._bkgchisqrplot = sherpa.astro.plot.BkgChisqrPlot()
        self._bkgdelchiplot = sherpa.astro.plot.BkgDelchiPlot()
        self._bkgresidplot = sherpa.astro.plot.BkgResidPlot()
        self._bkgratioplot = sherpa.astro.plot.BkgRatioPlot()
        self._bkgsourceplot = sherpa.astro.plot.BkgSourcePlot()
        self._arfplot = sherpa.astro.plot.ARFPlot()
        self._orderplot = sherpa.astro.plot.OrderPlot()
        self._energyfluxplot = sherpa.astro.plot.EnergyFluxHistogram()
        self._photonfluxplot = sherpa.astro.plot.PhotonFluxHistogram()

        # This is a new dictionary of XSPEC module settings.  It
        # is meant only to be populated by the save function, so
        # that the user's XSPEC settings can be saved in the pickle
        # file.  Then, restore can peel out settings from the
        # restored _xspec_state variable, and set abundance,
        # cross-section, etc. in the XSPEC module.
        self._xspec_state = None
        
        sherpa.ui.utils.Session.__init__(self)

        self._plot_types['order']=self._orderplot
        self._plot_types['energy']=self._energyfluxplot
        self._plot_types['photon']=self._photonfluxplot
        self._plot_types['astrocompsource']=self._astrocompsrcplot
        self._plot_types['astrocompmodel']=self._astrocompmdlplot

        self._plot_types['astrosource']=self._astrosourceplot
        self._plot_types['astromodel']=self._modelhisto
        self._plot_types['arf']=self._arfplot
        self._plot_types['bkg']=self._bkgdataplot
        self._plot_types['bkgmodel']=self._bkgmodelhisto
        self._plot_types['bkgfit']=self._bkgfitplot
        self._plot_types['bkgsource']=self._bkgsourceplot
        self._plot_types['bkgratio']=self._bkgratioplot
        self._plot_types['bkgresid']=self._bkgresidplot
        self._plot_types['bkgdelchi']=self._bkgdelchiplot
        self._plot_types['bkgchisqr']=self._bkgchisqrplot


    ###########################################################################
    # High-level utilities
    ###########################################################################

    def __setstate__(self, state):
        if not state.has_key('_background_sources'):
            self.__dict__['_background_sources'] = state.pop('_background_models')

        sherpa.ui.utils.Session.__setstate__(self, state)


    def clean(self):
        self._pileup_models     = {}
        self._background_models = {}
        self._background_sources = {}

        self._astrosourceplot= sherpa.astro.plot.SourcePlot()
        self._astrocompsrcplot = sherpa.astro.plot.ComponentSourcePlot()
        self._astrocompmdlplot = sherpa.astro.plot.ComponentModelPlot()
        self._modelhisto = sherpa.astro.plot.ModelHistogram()
        self._bkgmodelhisto = sherpa.astro.plot.BkgModelHistogram()

        self._bkgdataplot = sherpa.astro.plot.BkgDataPlot()
        self._bkgmodelplot = sherpa.astro.plot.BkgModelPlot()
        self._bkgfitplot = sherpa.astro.plot.BkgFitPlot()
        self._bkgchisqrplot = sherpa.astro.plot.BkgChisqrPlot()
        self._bkgdelchiplot = sherpa.astro.plot.BkgDelchiPlot()
        self._bkgresidplot = sherpa.astro.plot.BkgResidPlot()
        self._bkgratioplot = sherpa.astro.plot.BkgRatioPlot()
        self._bkgsourceplot = sherpa.astro.plot.BkgSourcePlot()
        self._arfplot = sherpa.astro.plot.ARFPlot()
        self._orderplot = sherpa.astro.plot.OrderPlot()
        self._energyfluxplot = sherpa.astro.plot.EnergyFluxHistogram()
        self._photonfluxplot = sherpa.astro.plot.PhotonFluxHistogram()

        self._xspec_state = None
        
        sherpa.ui.utils.Session.clean(self)

        self._plot_types['order']=self._orderplot
        self._plot_types['energy']=self._energyfluxplot
        self._plot_types['photon']=self._photonfluxplot
        self._plot_types['astrocompsource']=self._astrocompsrcplot
        self._plot_types['astrocompmodel']=self._astrocompmdlplot

        self._plot_types['astrosource']=self._astrosourceplot
        self._plot_types['astromodel']=self._modelhisto
        self._plot_types['arf']=self._arfplot
        self._plot_types['bkg']=self._bkgdataplot
        self._plot_types['bkgmodel']=self._bkgmodelhisto
        self._plot_types['bkgfit']=self._bkgfitplot
        self._plot_types['bkgsource']=self._bkgsourceplot
        self._plot_types['bkgratio']=self._bkgratioplot
        self._plot_types['bkgresid']=self._bkgresidplot
        self._plot_types['bkgdelchi']=self._bkgdelchiplot
        self._plot_types['bkgchisqr']=self._bkgchisqrplot

    # Add ability to save attributes sepcific to the astro package.
    # Save XSPEC module settings that need to be restored.
    def save(self, filename='sherpa.save', clobber=False):
        """
        save

        SYNOPSIS
           Save the current Sherpa session to a pickled file

        SYNTAX

        Arguments:
           filename   - name of save file
                        default = 'sherpa.save'           

           clobber    - clobber the file if it exists
                        default = False

        Returns:
           None

        DESCRIPTION
           Save the current Sherpa session information to a pickled file
           to be restored for future use.

        SEE ALSO
           restore, clean
        """
        if (hasattr(sherpa.astro, "xspec")):
            self._xspec_state = sherpa.astro.xspec.get_xsstate()
        else:
            self._xspec_state = None
        sherpa.ui.utils.Session.save(self, filename, clobber)

    def restore(self, filename='sherpa.save'):
        """
        restore

        SYNOPSIS
           Restore a previous Sherpa session from a pickled file

        SYNTAX

        Arguments:
           filename   - name of saved file
                        default = 'sherpa.save'           

        Returns:
           None

        DESCRIPTION
           Restore previous Sherpa session information from a pickled file
           for continued use.

        SEE ALSO
           save, clean
        """
        sherpa.ui.utils.Session.restore(self, filename)
        if (hasattr(sherpa.astro, "xspec")):
            if (self._xspec_state != None):
                sherpa.astro.xspec.set_xsstate(self._xspec_state)
                self._xspec_state = None
    
    def _get_show_data(self, id=None):
        data_str = ''
        ids = self.list_data_ids()
        if id is not None:
            ids = [self._fix_id(id)]
        for id in ids:
            data = self.get_data(id)

            data_str += 'Data Set: %s\n' % id
            data_str += 'Filter: %s\n' % data.get_filter_expr()
            if isinstance(data, sherpa.astro.data.DataPHA):

                scale = data.get_background_scale()
                if scale is not None and 