# -*- coding: utf-8 -*-
"""
@author: Laura C. Kühle

TODO: Give option to select plotting color

"""

import os
import time
import json
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
from numpy import ndarray
from sympy import Symbol

from Quadrature import Quadrature
from Initial_Condition import InitialCondition
from Basis_Function import Basis, OrthonormalLegendre
from projection_utils import calculate_exact_solution,\
    calculate_approximate_solution, Mesh
from encoding_utils import decode_ndarray


matplotlib.use('Agg')
x = Symbol('x')
z = Symbol('z')
sns.set()


def plot_solution_and_approx(grid: ndarray, exact: ndarray, approx: ndarray,
                             color_exact: str, color_approx: str) -> None:
    """Plots approximate and exact solution against each other.

    Parameters
    ----------
    grid : ndarray
        List of mesh evaluation points.
    exact : ndarray
        Array containing exact evaluation of a function.
    approx : ndarray
        Array containing approximate evaluation of a function.
    color_exact : str
        String describing color to plot exact solution.
    color_approx : str
        String describing color to plot approximate solution.

    """
    print(color_exact, color_approx)
    plt.figure('exact_and_approx')
    plt.plot(grid[0], exact[0], color_exact)
    plt.plot(grid[0], approx[0], color_approx)
    plt.xlabel('x')
    plt.ylabel('u(x,t)')
    plt.title('Solution and Approximation')


def plot_semilog_error(grid: ndarray, pointwise_error: ndarray) -> None:
    """Plots semi-logarithmic error between approximate and exact solution.

    Parameters
    ----------
    grid : ndarray
        List of mesh evaluation points.
    pointwise_error : ndarray
        Array containing pointwise difference between exact and approximate
        solution.

    """
    plt.figure('semilog_error')
    plt.semilogy(grid[0], pointwise_error[0])
    plt.xlabel('x')
    plt.ylabel('|u(x,t)-uh(x,t)|')
    plt.title('Semilog Error plotted at Evaluation points')


def plot_error(grid: ndarray, exact: ndarray, approx: ndarray) -> None:
    """Plots error between approximate and exact solution.

    Parameters
    ----------
    grid : ndarray
        List of mesh evaluation points.
    exact : ndarray
        Array containing exact evaluation of a function.
    approx : ndarray
        Array containing approximate evaluation of a function.

    """
    plt.figure('error')
    plt.plot(grid[0], exact[0]-approx[0])
    plt.xlabel('X')
    plt.ylabel('u(x,t)-uh(x,t)')
    plt.title('Errors')


def plot_shock_tube(num_grid_cells: int, troubled_cell_history: list,
                    time_history: list) -> None:
    """Plots shock tube.

    Plots detected troubled cells over time to depict the evolution of shocks
    as shock tubes.

    Parameters
    ----------
    num_grid_cells : int
        Number of cells in the mesh. Usually exponential of 2.
    troubled_cell_history : list
        List of detected troubled cells for each time step.
    time_history : list
        List of value of each time step.

    """
    plt.figure('shock_tube')
    for pos in range(len(time_history)):
        current_cells = troubled_cell_history[pos]
        for cell in current_cells:
            plt.plot(cell, time_history[pos], 'k.')
    plt.xlim((0, num_grid_cells))
    plt.xlabel('Cell')
    plt.ylabel('Time')
    plt.title('Shock Tubes')


def plot_details(fine_projection: ndarray, fine_mesh: Mesh, basis: Basis,
                 coarse_projection: ndarray,
                 multiwavelet_coeffs: ndarray) -> None:
    """Plots details of projection to coarser mesh.

    Parameters
    ----------
    fine_projection, coarse_projection : ndarray
        Matrix of projection for each polynomial degree.
    fine_mesh : Mesh
        Fine mesh for evaluation.
    basis: Basis object
        Basis used for calculation.
    multiwavelet_coeffs : ndarray
        Matrix of multiwavelet coefficients.

    """
    num_coarse_grid_cells = len(coarse_projection[0])
    averaged_projection = [[coarse_projection[degree][cell]
                            * basis.basis[degree].subs(x, value)
                            for cell in range(num_coarse_grid_cells)
                            for value in [-0.5, 0.5]]
                           for degree in range(basis.polynomial_degree + 1)]

    wavelet_projection = [[multiwavelet_coeffs[degree][cell]
                           * basis.wavelet[degree].subs(z, 0.5) * value
                           for cell in range(num_coarse_grid_cells)
                           for value in [(-1) ** (basis.polynomial_degree
                                                  + degree + 1), 1]]
                          for degree in range(basis.polynomial_degree + 1)]

    projected_coarse = np.sum(averaged_projection, axis=0)
    projected_fine = np.sum([fine_projection[degree]
                             * basis.basis[degree].subs(x, 0)
                             for degree in range(basis.polynomial_degree + 1)],
                            axis=0)
    projected_wavelet_coeffs = np.sum(wavelet_projection, axis=0)

    plt.figure('coeff_details')
    plt.plot(fine_mesh.non_ghost_cells, projected_fine-projected_coarse, 'm-.')
    plt.plot(fine_mesh.non_ghost_cells, projected_wavelet_coeffs, 'y')
    plt.legend(['Fine-Coarse', 'Wavelet Coeff'])
    plt.xlabel('X')
    plt.ylabel('Detail Coefficients')
    plt.title('Wavelet Coefficients')


def plot_classification_barplot(evaluation_dict: dict, colors: dict) -> None:
    """Plots classification accuracy.

    Plots given evaluation measures in a bar plot for each model.

    Parameters
    ----------
    evaluation_dict : dict
        Dictionary containing classification evaluation data.
    colors : dict
        Dictionary containing plotting colors.

    """
    model_names = evaluation_dict[list(colors.keys())[0]].keys()
    font_size = 16 - (len(max(model_names, key=len))//3)
    pos = np.arange(len(model_names))
    width = 1/(3*len(model_names))
    fig = plt.figure('barplot')
    ax = fig.add_axes([0.15, 0.3, 0.6, 0.6])
    step_len = 1
    adjustment = -(len(model_names)//2)*step_len
    for measure in evaluation_dict:
        model_eval = [evaluation_dict[measure][model]
                      for model in evaluation_dict[measure]]
        ax.bar(pos + adjustment*width, model_eval, width, label=measure,
               color=colors[measure])
        adjustment += step_len
    ax.set_xticks(pos)
    ax.set_xticklabels(model_names, rotation=50, ha='right',
                       fontsize=font_size)
    ax.set_ylabel('Classification (%)')
    ax.set_ylim(bottom=-0.02)
    ax.set_ylim(top=1.02)
    ax.set_title('Classification Evaluation (Barplot)')
    ax.legend(loc='center right', bbox_to_anchor=(1.4, 0.75), shadow=True,
              ncol=1, fancybox=True, fontsize=8)


def plot_classification_boxplot(evaluation_dict: dict, colors: dict) -> None:
    """Plots classification accuracy.

    Plots given evaluation measures in a boxplot for each model.

    Parameters
    ----------
    evaluation_dict : dict
        Dictionary containing classification evaluation data.
    colors : dict
        Dictionary containing plotting colors.

    """
    model_names = evaluation_dict[list(colors.keys())[0]].keys()
    font_size = 16 - (len(max(model_names, key=len))//3)
    fig = plt.figure('boxplot')
    ax = fig.add_axes([0.15, 0.3, 0.6, 0.6])
    step_len = 1.5
    boxplots = []
    adjustment = -(len(model_names)//2)*step_len
    pos = np.arange(len(model_names))
    width = 1/(5*len(model_names))
    for measure in evaluation_dict:
        model_eval = [evaluation_dict[measure][model]
                      for model in evaluation_dict[measure]]
        boxplot = ax.boxplot(model_eval, positions=pos + adjustment*width,
                             widths=width, meanline=True, showmeans=True,
                             patch_artist=True)
        for patch in boxplot['boxes']:
            patch.set(facecolor=colors[measure])
        boxplots.append(boxplot)
        adjustment += step_len

    ax.set_xticks(pos)
    ax.set_xticklabels(model_names, rotation=50, ha='right',
                       fontsize=font_size)
    ax.set_ylim(bottom=-0.02)
    ax.set_ylim(top=1.02)
    ax.set_ylabel('Classification (%)')
    ax.set_title('Classification Evaluation (Boxplot)')
    ax.legend([bp["boxes"][0] for bp in boxplots], evaluation_dict.keys(),
              loc='center right', bbox_to_anchor=(1.4, 0.75), shadow=True,
              ncol=1, fancybox=True, fontsize=8)


def plot_evaluation_results(evaluation_file: str, directory: str,
                            colors: dict = None) -> None:
    """Plots given evaluation results of model classifications.

    Plots evaluation results for all measures for which a color is given. If
    colors is set to None, all measures are plotted with a default color
    scheme.

    Parameters
    ----------
    evaluation_file: str
        Path to file containing evaluation results.
    directory : str
        Path to directory for saving resulting plots.
    colors : dict, optional
        Dictionary containing plotting colors. If None, set to default colors.
        Default: None.

    """
    tic = time.perf_counter()

    # Set colors if not given
    if colors is None:
        colors = {'Accuracy': 'magenta', 'Precision_Smooth': 'red',
                  'Precision_Troubled': '#8B0000', 'Recall_Smooth': 'blue',
                  'Recall_Troubled': '#00008B', 'F-Score_Smooth': 'green',
                  'F-Score_Troubled': '#006400', 'AUROC': 'yellow'}

    # Read evaluation results
    print('Reading evaluation results.')
    with open(evaluation_file) as json_file:
        classification_stats = json.load(json_file)

    # Plot data
    print('\nPlotting evaluation of trained models...')
    print('Plotting data in boxplot.')
    models = classification_stats[list(colors.keys())[0]].keys()
    plot_classification_boxplot(classification_stats, colors)
    print('Plotting averaged data in barplot.')
    classification_stats = {measure: {model: np.array(
        classification_stats[measure][model]).mean()
                                      for model in models}
                            for measure in colors}
    plot_classification_barplot(classification_stats, colors)
    print('Finished plotting evaluation of trained models!\n')

    # Set paths for plot files if not existing already
    plot_dir = directory + '/model evaluation'
    if not os.path.exists(plot_dir):
        os.makedirs(plot_dir)

    # Save plots
    print('Saving plots.')
    file_name = evaluation_file.split('/')[-1].rstrip('.json')
    for identifier in plt.get_figlabels():
        plt.figure(identifier)
        plt.savefig(plot_dir + '/' + file_name + '.' + identifier + '.pdf')
    toc = time.perf_counter()
    print(f'Total runtime: {toc - tic:0.4f}s')


def plot_approximation_results(data_file: str, directory: str, plot_name: str,
                               quadrature: Quadrature,
                               init_cond: InitialCondition) -> None:
    """Plots given approximation results.

    Generates plots based on given data, sets plot directory if not
    already existing, and saves plots.

    Parameters
    ----------
    data_file: str
        Path to data file for plotting.
    directory: str
        Path to directory in which plots will be saved.
    plot_name : str
        Name of plot.
    quadrature: Quadrature object
        Quadrature used for evaluation.
    init_cond : InitialCondition object
        Initial condition used for calculation.

    """
    # Read approximation results
    with open(data_file + '.json') as json_file:
        approx_stats = json.load(json_file)

    # Decode all ndarrays by converting lists
    approx_stats = {key: decode_ndarray(approx_stats[key])
                    for key in approx_stats.keys()}
    approx_stats['basis'] = OrthonormalLegendre(**approx_stats['basis'])
    approx_stats['mesh'] = Mesh(**approx_stats['mesh'])

    # Plot exact/approximate results, errors, shock tubes,
    # and any detector-dependant plots
    plot_results(quadrature=quadrature, init_cond=init_cond, **approx_stats)

    # Set paths for plot files if not existing already
    if not os.path.exists(directory):
        os.makedirs(directory)

    # Save plots
    for identifier in plt.get_figlabels():
        # Set path for figure directory if not existing already
        if not os.path.exists(directory + '/' + identifier):
            os.makedirs(directory + '/' + identifier)

        plt.figure(identifier)
        plt.savefig(directory + '/' + identifier + '/' +
                    plot_name + '.pdf')


def plot_results(projection: ndarray, troubled_cell_history: list,
                 time_history: list, mesh: Mesh, wave_speed: float,
                 final_time: float, basis: Basis,
                 quadrature: Quadrature, init_cond: InitialCondition,
                 colors: dict = None, coarse_projection: ndarray = None,
                 multiwavelet_coeffs: ndarray = None) -> None:
    """Plots results and troubled cells of a projection.

    Plots exact and approximate solution, errors, and troubled cells of a
    projection given its evaluation history.

    If coarse grid and projection are given, solutions are displayed for
    both coarse and fine grid. Additionally, coefficient details are plotted.

    Parameters
    ----------
    projection : ndarray
        Matrix of projection for each polynomial degree.
    troubled_cell_history : list
        List of detected troubled cells for each time step.
    time_history : list
        List of value of each time step.
    mesh : Mesh
        Mesh for calculation.
    wave_speed : float
        Speed of wave in rightward direction.
    final_time : float
        Final time for which approximation is calculated.
    basis: Vector object
        Basis used for calculation.
    quadrature: Quadrature object
        Quadrature used for evaluation.
    init_cond : InitialCondition object
        Initial condition used for calculation.
    colors: dict
        Dictionary of colors used for plots.
    coarse_projection: ndarray, optional
        Matrix of projection on coarse grid for each polynomial degree.
        Default: None.
    multiwavelet_coeffs: ndarray, optional
        Matrix of wavelet coefficients. Default: None.

    """
    # Set colors
    if colors is None:
        colors = {}
    colors = _check_colors(colors)

    # Plot troubled cells
    plot_shock_tube(mesh.num_grid_cells, troubled_cell_history, time_history)

    # Determine exact and approximate solution
    grid, exact = calculate_exact_solution(
        mesh, wave_speed, final_time, quadrature, init_cond)
    approx = calculate_approximate_solution(
        projection[:, 1:-1], quadrature.nodes,
        basis.polynomial_degree, basis.basis)

    # Plot multiwavelet solution (fine and coarse grid)
    if coarse_projection is not None:
        coarse_mesh = Mesh(num_grid_cells=mesh.num_grid_cells//2,
                           num_ghost_cells=1, left_bound=mesh.bounds[0],
                           right_bound=mesh.bounds[1])

        # Plot exact and approximate solutions for coarse mesh
        coarse_grid, coarse_exact = calculate_exact_solution(
            coarse_mesh, wave_speed, final_time, quadrature, init_cond)
        coarse_approx = calculate_approximate_solution(
            coarse_projection, quadrature.nodes,
            basis.polynomial_degree, basis.basis)
        plot_solution_and_approx(
            coarse_grid, coarse_exact, coarse_approx, colors['coarse_exact'],
            colors['coarse_approx'])

        # Plot multiwavelet details
        plot_details(projection[:, 1:-1], mesh, basis, coarse_projection,
                     multiwavelet_coeffs)

        plot_solution_and_approx(grid, exact, approx,
                                 colors['fine_exact'],
                                 colors['fine_approx'])
        plt.legend(['Exact (Coarse)', 'Approx (Coarse)', 'Exact (Fine)',
                    'Approx (Fine)'])
    # Plot regular solution (fine grid)
    else:
        plot_solution_and_approx(grid, exact, approx, colors['exact'],
                                 colors['approx'])
        plt.legend(['Exact', 'Approx'])

    # Calculate errors
    pointwise_error = np.abs(exact-approx)
    max_error = np.max(pointwise_error)

    # Plot errors
    plot_semilog_error(grid, pointwise_error)
    plot_error(grid, exact, approx)

    print('p =', basis.polynomial_degree)
    print('N =', mesh.num_grid_cells)
    print('maximum error =', max_error)


def _check_colors(colors: dict) -> dict:
    """Checks plot colors.

    Checks whether colors for plots were given and sets them if required.

    Parameters
    ----------
    colors: dict
        Dictionary containing color strings for plotting.

    Returns
    -------
    dict
        Dictionary containing color strings for plotting.


    """
    # Set colors for general plots
    colors['exact'] = colors.get('exact', 'k-')
    colors['approx'] = colors.get('approx', 'y')

    # Set colors for multiwavelet plots
    colors['fine_exact'] = colors.get('fine_exact', 'k-.')
    colors['fine_approx'] = colors.get('fine_approx', 'b-.')
    colors['coarse_exact'] = colors.get('coarse_exact', 'k-')
    colors['coarse_approx'] = colors.get('coarse_approx', 'y')

    return colors