# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017-2019 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
"""simple helper function to link io module and XASObject"""

__authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "07/16/2019"


from est.io import read_xas, write_xas, get_xasproc
from est.core.types import XASObject
from silx.io.url import DataUrl
import h5py
import logging

_logger = logging.getLogger(__name__)

DEFAULT_SPECTRA_PATH = '/data/NXdata/data'

DEFAULT_CHANNEL_PATH = '/data/NXdata/Channel'

DEFAULT_CONF_PATH = '/configuration'


def read(spectra_url, channel_url, config_url=None):
    """
    
    :param DataUrl spectra_url: data url to the spectra
    :param DataUrl channel_url: data url to the channel / energy
    :param DataUrl config_url: data url to the process configuration
    :return: 
    :rtype: XASObject
    """
    reader = XASReader()
    return reader.read_frm_url(spectra_url=spectra_url, channel_url=channel_url,
                               config_url=config_url)


def read_frm_file(file_path):
    """
    
    :param str file_path: path to the file containing the spectra. Must ba a
                          .dat file that pymca can handle or a .h5py with
                          default path
    :rtype: XASObject
    """
    reader = XASReader()
    return reader.read_from_file(file_path=file_path)


class XASReader(object):
    """Simple reader of a xas file"""
    def read_frm_url(self, spectra_url, channel_url, config_url=None):
        sp, en, conf = read_xas(spectra_url=spectra_url,
                                channel_url=channel_url,
                                config_url=config_url)
        return XASObject(spectra=sp, energy=en, configuration=conf)

    def read_from_file(self, file_path):
        """

        :param str file_path: 
        :return: `.XASObject`
        """
        if file_path.endswith('.dat'):
            return self.read_frm_url(
                    spectra_url=DataUrl(file_path=file_path,
                                        scheme='PyMca'),
                    channel_url=DataUrl(file_path=file_path,
                                        scheme='PyMca'))
        elif file_path.endswith('.xmu'):
            return self.read_frm_url(
                    spectra_url=DataUrl(file_path=file_path,
                                        scheme='larch'),
                    channel_url=DataUrl(file_path=file_path,
                                        scheme='larch'))
        elif h5py.is_hdf5(file_path):
            return self.read_frm_url(
                    spectra_url=DataUrl(file_path=file_path,
                                        scheme='silx',
                                        data_path=DEFAULT_SPECTRA_PATH),
                    channel_url=DataUrl(file_path=file_path,
                                        scheme='silx',
                                        data_path=DEFAULT_CHANNEL_PATH),
                    config_url=DataUrl(file_path=file_path,
                                       scheme='silx',
                                       data_path='configuration'))
        else:
            raise ValueError('file type not managed, unable to load')

    __call__ = read_from_file



class XASWriter(object):
    """
    class to write the output file. In this case we need a class in order to
    setup the output file before
    """
    def __init__(self):
        self._output_file = None

    @property
    def output_file(self):
        return self._output_file

    @output_file.setter
    def output_file(self, file_):
        self._output_file = file_

    def setProperties(self, properties):
        if '_output_file_setting' in properties:
            self._output_file = properties['_output_file_setting']

    def dump_xas(self, xas_obj, write_process=True):
        """
        write the XASObject into a hdf5 file.

        :param xas_obj: object to be stored
        :type: Union[:class:`.XASObject`,dict]
        :param bool write_process: if True then store the process flow in the
            same file.
        """
        if isinstance(xas_obj, dict):
            _xas_obj = XASObject.from_dict(xas_obj)
        else:
            _xas_obj = xas_obj

        if not self._output_file:
            _logger.warning('no output file defined, please give path to the'
                            'output file')
            self._output_file = input()

        _logger.info(('dump xas obj to', self._output_file))

        # write raw data
        write_xas(h5_file=self._output_file, energy=_xas_obj.energy,
                  mu=_xas_obj.absorbed_beam(), entry=_xas_obj.entry)

        if write_process is True:
            if len(get_xasproc(self._output_file, entry=_xas_obj.entry)) > 0:
                _logger.warning('removing previous process registred. They are no '
                                'more accurate')
                _xas_obj.clean_process_flow()

            # write process flow
            _xas_obj.copy_process_flow_to(self._output_file)

    __call__ = dump_xas
