""" DSSC visualization routines

Plotting sub-routines frequently done in combination with dssc analysis. 
The initial code is based on: https://github.com/dscran/dssc_process
/blob/master/example_image_process_pulsemask.ipynb

Todo: For visualization of statistical information we could eventually 
switch to seaborn: https://seaborn.pydata.org/
"""

from time import strftime

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr


def plot_xgm_threshold(xgm,
                       xgm_min = None, xgm_max = None,
                       run_nr = '', safe_fig = False):

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.plot(xgm.trainId, xgm, 'o', c='C0', ms=1)
    if xgm_min:
        ax.axhline(xgm_min, c='r')
    if xgm_max:
        ax.axhline(xgm_max, c='r')

    ax.set_xlabel('trainId')
    ax.set_ylabel('xgm')
    ax.set_title(f'run: {run_nr}')

    if safe_fig == True:
        tstamp = strftime('%y%m%d_%H%M')
        fig.savefig(f'images/run{run_nr}_scan_{tstamp}.png', dpi=200)


def plot_binner(binner,
                yname = 'data', xname='data',
                run_nr = ''):

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.plot(binner.values)

    ax.set_ylabel(yname)
    ax.set_xlabel(xname)
    ax.set_title(f'run: {run_nr}')


def plot_binner_hist(binner,
                 dname = 'data', run_nr = ''):

    counts = xr.DataArray(np.ones(len(binner.values)),
                      dims=[dname],
                      coords={dname: binner.values},
                      name='counts')

    counts = counts.groupby(dname).sum()

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.plot(counts[dname], counts, 'o', ms=4)

    ax.set_xlabel(dname)
    ax.set_ylabel('counts')
    ax.set_title(f'run {run_nr}')
    ax.grid(True)

    #if safe_fig == True:
    #    tstamp = strftime('%y%m%d_%H%M')
    #    fig.savefig(f'images/run{run_nr}_scan_{tstamp}.png', dpi=200)


def plot_hist_processed(hist_data):
    pass