#!/usr/bin/env python
#
# Copyright 2014 Knowledge Economy Developments Ltd
# Copyright 2014 David Wells
#
# Henry Gomersall
# heng@kedevelopments.co.uk
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

'''
A set of utility functions for use with the builders. Users should
not need to use the functions directly, but they are included here for
completeness and to aid with understanding of what is happening behind
the scenes.

Certainly, users may encounter instances of
:class:`~pyfftw.builders._utils._FFTWWrapper`.

Everything documented in this module is *not* part of the public API
and may change in future versions.
'''

import multiprocessing
import pyfftw
import numpy
import warnings
from .. import _threading_type
from .. import config

__all__ = ['_FFTWWrapper', '_rc_dtype_pairs', '_default_dtype', '_Xfftn',
        '_setup_input_slicers', '_compute_array_shapes', '_precook_1d_args',
        '_cook_nd_args']

_valid_efforts = ('FFTW_ESTIMATE', 'FFTW_MEASURE',
        'FFTW_PATIENT', 'FFTW_EXHAUSTIVE')

_real_to_real_dtypes = [numpy.dtype('float32'), numpy.dtype('float64'),
                        numpy.dtype('longdouble')]

# Looking up a real dtype in here returns the complex complement of the same
# precision, and vice versa.

# It is necessary to use .char as the keys due to MSVC mapping long
# double to double and the way that numpy handles this.
_rc_dtype_pairs = {}
_default_dtype = None

# Double precision is the default default precision. Prefer casting to higher precision if
# possible. If missing, long double is mapped to double and so we lose less
# precision than by converting to single.
if '64' in pyfftw._supported_types:
    _default_dtype = numpy.dtype('float64')
    _rc_dtype_pairs.update({
        numpy.dtype('float64').char: numpy.dtype('complex128'),
        numpy.dtype('complex128').char: numpy.dtype('float64')})
if 'ld' in pyfftw._supported_types:
    if _default_dtype is None:
        _default_dtype = numpy.dtype('longdouble')
    _rc_dtype_pairs.update({
         numpy.dtype('longdouble').char: numpy.dtype('clongdouble'),
         numpy.dtype('clongdouble').char: numpy.dtype('longdouble')})
if '32' in pyfftw._supported_types:
    if _default_dtype is None:
        _default_dtype = numpy.dtype('float32')
    _rc_dtype_pairs.update({
        numpy.dtype('float32').char: numpy.dtype('complex64'),
        numpy.dtype('complex64').char: numpy.dtype('float32')})
if _default_dtype is None:
    raise NotImplementedError("No default precision available")


def _default_effort(effort):
    if effort is None:
        return config.PLANNER_EFFORT
    else:
        return effort


def _default_threads(threads):
    if threads is None:
        if config.NUM_THREADS <= 0:
            return multiprocessing.cpu_count()
        return config.NUM_THREADS
    else:
        if threads > 1 and _threading_type is None:
            raise ValueError("threads > 1 requested, but pyFFTW was not built "
                             "with multithreaded FFTW.")
        elif threads <= 0:
            return multiprocessing.cpu_count()
        return threads


def _unitary(norm):
    """_unitary() utility copied from numpy"""
    if norm not in (None, "ortho"):
        raise ValueError("Invalid norm value %s, should be None or \"ortho\"."
                         % norm)
    return norm is not None


def _norm_args(norm):
    """ pass the proper normalization-related keyword arguments. """
    if _unitary(norm):
        ortho = True
        normalise_idft = False
    else:
        ortho = False
        normalise_idft = True
    return dict(normalise_idft=normalise_idft, ortho=ortho)


def _Xfftn(a, s, axes, overwrite_input,