"""Functions to plot ICA specific data (besides topographies)."""
from __future__ import print_function

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Teon Brooks <teon.brooks@gmail.com>
#
# License: Simplified BSD

from functools import partial
from numbers import Integral

import numpy as np

from .utils import (tight_layout, _prepare_trellis, _select_bads,
                    _layout_figure, _plot_raw_onscroll, _mouse_click,
                    _helper_raw_resize, _plot_raw_onkey, plt_show)
from .topomap import (_prepare_topo_plot, plot_topomap, _hide_frame,
                      _plot_ica_topomap)
from .raw import _prepare_mne_browse_raw, _plot_raw_traces, _convert_psds
from .epochs import _prepare_mne_browse_epochs, plot_epochs_image
from .evoked import _butterfly_on_button_press, _butterfly_onpick
from ..utils import warn, _validate_type
from ..defaults import _handle_default
from ..io.meas_info import create_info
from ..io.pick import pick_types
from ..externals.six import string_types
from ..time_frequency.psd import psd_multitaper


def plot_ica_sources(ica, inst, picks=None, exclude=None, start=None,
                     stop=None, title=None, show=True, block=False,
                     show_first_samp=False):
    """Plot estimated latent sources given the unmixing matrix.

    Typical usecases:

    1. plot evolution of latent sources over time based on (Raw input)
    2. plot latent source around event related time windows (Epochs input)
    3. plot time-locking in ICA space (Evoked input)


    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    inst : instance of mne.io.Raw, mne.Epochs, mne.Evoked
        The object to plot the sources from.
    picks : int | array_like of int | None.
        The components to be displayed. If None, plot will show the
        sources in the order as fitted.
    exclude : array_like of int
        The components marked for exclusion. If None (default), ICA.exclude
        will be used.
    start : int
        X-axis start index. If None, from the beginning.
    stop : int
        X-axis stop index. If None, next 20 are shown, in case of evoked to the
        end.
    title : str | None
        The figure title. If None a default is provided.
    show : bool
        Show figure if True.
    block : bool
        Whether to halt program execution until the figure is closed.
        Useful for interactive selection of components in raw and epoch
        plotter. For evoked, this parameter has no effect. Defaults to False.
    show_first_samp : bool
        If True, show time axis relative to the ``raw.first_samp``.

    Returns
    -------
    fig : instance of pyplot.Figure
        The figure.

    Notes
    -----
    For raw and epoch instances, it is possible to select components for
    exclusion by clicking on the line. The selected components are added to
    ``ica.exclude`` on close.

    .. versionadded:: 0.10.0
    """
    from ..io.base import BaseRaw
    from ..evoked import Evoked
    from ..epochs import BaseEpochs

    if exclude is None:
        exclude = ica.exclude
    elif len(ica.exclude) > 0:
        exclude = np.union1d(ica.exclude, exclude)
    if isinstance(inst, BaseRaw):
        fig = _plot_sources_raw(ica, inst, picks, exclude, start=start,
                                stop=stop, show=show, title=title,
                                block=block, show_first_samp=show_first_samp)
    elif isinstance(inst, BaseEpochs):
        fig = _plot_sources_epochs(ica, inst, picks, exclude, start=start,
                                   stop=stop, show=show, title=title,
                                   block=block)
    elif isinstance(inst, Evoked):
        if start is not None or stop is not None:
            inst = inst.copy().crop(start, stop)
        sources = ica.get_sources(inst)
        fig = _plot_ica_sources_evoked(
            evoked=sources, picks=picks, exclude=exclude, title=title,
            labels=getattr(ica, 'labels_', None), show=show, ica=ica)
    else:
        raise ValueError('Data input must be of Raw or Epochs type')

    return fig


def _create_properties_layout(figsize=None):
    """Create main figure and axes layout used by plot_ica_properties."""
    import matplotlib.pyplot as plt
    if figsize is None:
        figsize = [7., 6.]
    fig = plt.figure(figsize=figsize, facecolor=[0.95] * 3)

    axes_params = (('topomap', [0.08, 0.5, 0.3, 0.45]),
                   ('image', [0.5, 0.6, 0.45, 0.35]),
                   ('erp', [0.5, 0.5, 0.45, 0.1]),
                   ('spectrum', [0.08, 0.1, 0.32, 0.3]),
                   ('variance', [0.5, 0.1, 0.45, 0.25]))
    axes = [fig.add_axes(loc, label=name) for name, loc in axes_params]

    return fig, axes


def _plot_ica_properties(pick, ica, inst, psds_mean, freqs, n_trials,
                         epoch_var, plot_lowpass_edge, epochs_src,
                         set_title_and_labels, plot_std, psd_ylabel,
                         spectrum_std, topomap_args, image_args, fig, axes):
    """Plot ICA properties (helper)."""
    topo_ax, image_ax, erp_ax, spec_ax, var_ax = axes

    # plotting
    # --------
    # component topomap
    _plot_ica_topomap(ica, pick, show=False, axes=topo_ax, **topomap_args)

    # image and erp
    plot_epochs_image(epochs_src, picks=pick, axes=[image_ax, erp_ax],
                      combine=None, colorbar=False, show=False, **image_args)

    # spectrum
    spec_ax.plot(freqs, psds_mean, color='k')
    if plot_std:
        spec_ax.fill_between(freqs, psds_mean - spectrum_std[0],
                             psds_mean + spectrum_std[1],
                             color='k', alpha=.2)
    if plot_lowpass_edge:
        spec_ax.axvline(inst.info['lowpass'], lw=2, linestyle='--',
                        color='k', alpha=0.2)

    # epoch variance
    var_ax.scatter(range(len(epoch_var)), epoch_var, alpha=0.5,
                   facecolor=[0, 0, 0], lw=0)

    # aesthetics
    # ----------
    topo_ax.set_title(ica._ica_names[pick])

    set_title_and_labels(image_ax, 'Epochs image and ERP/ERF', [], 'Epochs')

    # erp
    set_title_and_labels(erp_ax, [], 'Time (s)', 'AU\n')
    erp_ax.spines["right"].set_color('k')
    erp_ax.set_xlim(epochs_src.times[[0, -1]])
    # remove half of yticks if more than 5
    yt = erp_ax.get_yticks()
    if len(yt) > 5:
        yt = yt[::2]
        erp_ax.yaxis.set_ticks(yt)

    # remove xticks - erp plot shows xticks for both image and erp plot
    image_ax.xaxis.set_ticks([])
    yt = image_ax.get_yticks()
    image_ax.yaxis.set_ticks(yt[1:])
    image_ax.set_ylim([-0.5, n_trials + 0.5])

    # spectrum
    set_title_and_labels(spec_ax, 'Spectrum', 'Frequency (Hz)', psd_ylabel)
    spec_ax.yaxis.labelpad = 0
    spec_ax.set_xlim(freqs[[0, -1]])
    ylim = spec_ax.get_ylim()
    air = np.diff(ylim)[0] * 0.1
    spec_ax.set_ylim(ylim[0] - air, ylim[1] + air)
    image_ax.axhline(0, color='k', linewidth=.5)

    # epoch variance
    set_title_and_labels(var_ax, 'Epochs variance', 'Epoch (index)', 'AU')

    return fig


def _get_psd_label_and_std(this_psd, dB, ica, num_std):
    """Handle setting up PSD for one component, for plot_ica_properties."""
    psd_ylabel = _convert_psds(this_psd, dB, estimate='auto', scaling=1.,
                               unit='AU', ch_names=ica.ch_names)
    psds_mean = this_psd.mean(axis=0)
    diffs = this_psd - psds_mean
    # the distribution of power for each frequency bin is highly
    # skewed so we calculate std for values below and above average
    # separately - this is used for fill_between shade
    spectrum_std = [
        [np.sqrt((d[d < 0] ** 2).mean(axis=0)) for d in diffs.T],
        [np.sqrt((d[d > 0] ** 2).mean(axis=0)) for d in diffs.T]]
    spectrum_std = np.array(spectrum_std) * num_std

    return psd_ylabel, psds_mean, spectrum_std


def plot_ica_properties(ica, inst, picks=None, axes=None, dB=True,
                        plot_std=True, topomap_args=None, image_args=None,
                        psd_args=None, figsize=None, show=True):
    """Display component properties.

    Properties include the topography, epochs image, ERP/ERF, power
    spectrum, and epoch variance.

    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    inst: instance of Epochs or Raw
        The data to use in plotting properties.
    picks : int | array-like of int | None
        The components to be displayed. If None, plot will show the first
        five sources. If more than one components were chosen in the picks,
        each one will be plotted in a separate figure. Defaults to None.
    axes: list of matplotlib axes | None
        List of five matplotlib axes to use in plotting: [topomap_axis,
        image_axis, erp_axis, spectrum_axis, variance_axis]. If None a new
        figure with relevant axes is created. Defaults to None.
    dB: bool
        Whether to plot spectrum in dB. Defaults to True.
    plot_std: bool | float
        Whether to plot standard deviation in ERP/ERF and spectrum plots.
        Defaults to True, which plots one standard deviation above/below.
        If set to float allows to control how many standard deviations are
        plotted. For example 2.5 will plot 2.5 standard deviation above/below.
    topomap_args : dict | None
        Dictionary of arguments to ``plot_topomap``. If None, doesn't pass any
        additional arguments. Defaults to None.
    image_args : dict | None
        Dictionary of arguments to ``plot_epochs_image``. If None, doesn't pass
        any additional arguments. Defaults to None.
    psd_args : dict | None
        Dictionary of arguments to ``psd_multitaper``. If None, doesn't pass
        any additional arguments. Defaults to None.
    figsize : array-like of size (2,) | None
        Allows to control size of the figure. If None, the figure size
        defaults to [7., 6.].
    show : bool
        Show figure if True.

    Returns
    -------
    fig : list
        List of matplotlib figures.

    Notes
    -----
    .. versionadded:: 0.13
    """
    from ..io.base import BaseRaw
    from ..epochs import BaseEpochs
    from ..preprocessing import ICA

    # input checks and defaults
    # -------------------------
    _validate_type(inst, (BaseRaw, BaseEpochs), "inst", "Raw or Epochs")
    _validate_type(ica, ICA, "ica", "ICA")
    if isinstance(plot_std, bool):
        num_std = 1. if plot_std else 0.
    elif isinstance(plot_std, (float, int)):
        num_std = plot_std
        plot_std = True
    else:
        raise ValueError('plot_std has to be a bool, int or float, '
                         'got %s instead' % type(plot_std))

    # if no picks given - plot the first 5 components
    picks = list(range(min(5, ica.n_components_))) if picks is None else picks
    picks = [picks] if isinstance(picks, Integral) else picks
    if axes is None:
        fig, axes = _create_properties_layout(figsize=figsize)
    else:
        if len(picks) > 1:
            raise ValueError('Only a single pick can be drawn '
                             'to a set of axes.')
        from .utils import _validate_if_list_of_axes
        _validate_if_list_of_axes(axes, obligatory_len=5)
        fig = axes[0].get_figure()
    psd_args = dict() if psd_args is None else psd_args
    topomap_args = dict() if topomap_args is None else topomap_args
    image_args = dict() if image_args is None else image_args
    image_args["ts_args"] = dict(truncate_xaxis=False, show_sensors=False)
    for item_name, item in (("psd_args", psd_args),
                            ("topomap_args", topomap_args),
                            ("image_args", image_args)):
        _validate_type(item, dict, item_name, "dictionary")
    if dB is not None:
        _validate_type(dB, bool, "dB", "bool")

    # calculations
    # ------------
    if isinstance(inst, BaseRaw):
        # break up continuous signal into segments
        from ..epochs import _segment_raw
        inst = _segment_raw(inst, segment_length=2., verbose=False,
                            preload=True)

    epochs_src = ica.get_sources(inst)
    ica_data = np.swapaxes(epochs_src.get_data()[:, picks, :], 0, 1)

    # spectrum
    Nyquist = inst.info['sfreq'] / 2.
    lp = inst.info['lowpass']
    if 'fmax' not in psd_args:
        psd_args['fmax'] = min(lp * 1.25, Nyquist)
    plot_lowpass_edge = lp < Nyquist and (psd_args['fmax'] > lp)
    psds, freqs = psd_multitaper(epochs_src, picks=picks, **psd_args)

    def set_title_and_labels(ax, title, xlab, ylab):
        if title:
            ax.set_title(title)
        if xlab:
            ax.set_xlabel(xlab)
        if ylab:
            ax.set_ylabel(ylab)
        ax.axis('auto')
        ax.tick_params('both', labelsize=8)
        ax.axis('tight')

    # plot
    # ----
    all_fig = list()
    for idx, pick in enumerate(picks):

        # calculate component-specific spectrum stuff
        psd_ylabel, psds_mean, spectrum_std = _get_psd_label_and_std(
            psds[:, idx, :].copy(), dB, ica, num_std)

        # if more than one component, spawn additional figures and axes
        if idx > 0:
            fig, axes = _create_properties_layout(figsize=figsize)

        # the actual plot
        fig = _plot_ica_properties(
            pick, ica, inst, psds_mean, freqs, ica_data.shape[1],
            np.var(ica_data[idx], axis=1), plot_lowpass_edge,
            epochs_src, set_title_and_labels, plot_std, psd_ylabel,
            spectrum_std, topomap_args, image_args, fig, axes)
        all_fig.append(fig)

    plt_show(show)
    return all_fig


def _plot_ica_sources_evoked(evoked, picks, exclude, title, show, ica,
                             labels=None):
    """Plot average over epochs in ICA space.

    Parameters
    ----------
    evoked : instance of mne.Evoked
        The Evoked to be used.
    picks : int | array_like of int | None.
        The components to be displayed. If None, plot will show the
        sources in the order as fitted.
    exclude : array_like of int
        The components marked for exclusion. If None (default), ICA.exclude
        will be used.
    title : str
        The figure title.
    show : bool
        Show figure if True.
    labels : None | dict
        The ICA labels attribute.
    """
    import matplotlib.pyplot as plt
    if title is None:
        title = 'Reconstructed latent sources, time-locked'

    fig, axes = plt.subplots(1)
    ax = axes
    axes = [axes]
    times = evoked.times * 1e3

    # plot unclassified sources and label excluded ones
    lines = list()
    texts = list()
    if picks is None:
        picks = np.arange(evoked.data.shape[0])
    picks = np.sort(picks)
    idxs = [picks]

    if labels is not None:
        labels_used = [k for k in labels if '/' not in k]

    exclude_labels = list()
    for ii in picks:
        if ii in exclude:
            line_label = ica._ica_names[ii]
            if labels is not None:
                annot = list()
                for this_label in labels_used:
                    indices = labels[this_label]
                    if ii in indices:
                        annot.append(this_label)

                line_label += (' - ' + ', '.join(annot))
            exclude_labels.append(line_label)
        else:
            exclude_labels.append(None)

    if labels is not None:
        # compute colors only based on label categories
        unique_labels = set([k.split(' - ')[1] for k in exclude_labels if k])
        label_colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_labels)))
        label_colors = dict(zip(unique_labels, label_colors))
    else:
        label_colors = dict((k, 'red') for k in exclude_labels)

    for exc_label, ii in zip(exclude_labels, picks):
        if exc_label is not None:
            # create look up for color ...
            if ' - ' in exc_label:
                key = exc_label.split(' - ')[1]
            else:
                key = exc_label
            color = label_colors[key]
            # ... but display component number too
            lines.extend(ax.plot(times, evoked.data[ii].T, picker=3.,
                         zorder=2, color=color, label=exc_label))
        else:
            lines.extend(ax.plot(times, evoked.data[ii].T, picker=3.,
                                 color='k', zorder=1))

    ax.set(title=title, xlim=times[[0, -1]], xlabel='Time (ms)', ylabel='(NA)')
    if len(exclude) > 0:
        plt.legend(loc='best')
    tight_layout(fig=fig)

    # for old matplotlib, we actually need this to have a bounding
    # box (!), so we have to put some valid text here, change
    # alpha and  path effects later
    texts.append(ax.text(0, 0, 'blank', zorder=3,
                         verticalalignment='baseline',
                         horizontalalignment='left',
                         fontweight='bold', alpha=0))
    # this is done to give the structure of a list of lists of a group of lines
    # in each subplot
    lines = [lines]
    ch_names = evoked.ch_names

    from matplotlib import patheffects
    path_effects = [patheffects.withStroke(linewidth=2, foreground="w",
                                           alpha=0.75)]
    params = dict(axes=axes, texts=texts, lines=lines, idxs=idxs,
                  ch_names=ch_names, need_draw=False,
                  path_effects=path_effects)
    fig.canvas.mpl_connect('pick_event',
                           partial(_butterfly_onpick, params=params))
    fig.canvas.mpl_connect('button_press_event',
                           partial(_butterfly_on_button_press,
                                   params=params))
    plt_show(show)
    return fig


def plot_ica_scores(ica, scores, exclude=None, labels=None, axhline=None,
                    title='ICA component scores', figsize=None, show=True):
    """Plot scores related to detected components.

    Use this function to asses how well your score describes outlier
    sources and how well you were detecting them.

    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA object.
    scores : array_like of float, shape (n ica components) | list of arrays
        Scores based on arbitrary metric to characterize ICA components.
    exclude : array_like of int
        The components marked for exclusion. If None (default), ICA.exclude
        will be used.
    labels : str | list | 'ecg' | 'eog' | None
        The labels to consider for the axes tests. Defaults to None.
        If list, should match the outer shape of `scores`.
        If 'ecg' or 'eog', the ``labels_`` attributes will be looked up.
        Note that '/' is used internally for sublabels specifying ECG and
        EOG channels.
    axhline : float
        Draw horizontal line to e.g. visualize rejection threshold.