import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Patch

labels = ['loop overhead',
          'function call',
          'stack switching',
          'setjmp and stack switching',
          'minimal fcontext overhead',
          'minimum callcc overhead',
          'custom assembly'
          ]

call_color = (0.3, 0.1, 0.4, 0.6)
setjmp_color = (0.3, 0.3, 0.4, 0.6)
fcontext_color = (0.3, 0.6, 0.4, 0.6)
custom_color = (0.3, 1.0, 0.4, 0.6)
colors = [
    call_color,
    call_color,
    setjmp_color,
    setjmp_color,
    fcontext_color,
    fcontext_color,
    custom_color
]

dataX86 = np.array([
    0.55,
    2.79,
    5.60,
    14.93,
    11.00,
    18.66,
    7.86,
])
dataARM32 = np.array([
    1.26,
    4.97,
    11.25,
    54.50,
    57.45,
    101.29,
    23.74,
])


def plot_data(data, name):
    plt.clf()

    # Make sure pgf plots have correct fonts
    pgf_with_rc_fonts = {
        "font.family": "serif",
        "font.serif": [""],
        "font.sans-serif": [""],
    }
    plt.rcParams.update(pgf_with_rc_fonts)

    xAxis = np.array(range(0, len(labels)))

    plt.bar(xAxis, data, color=colors)
    plt.xticks(xAxis, labels, rotation=90)
    plt.ylabel('runtime in ns')
    plt.subplots_adjust(bottom=0.5, top=0.98)

    custom_lines = [Patch(facecolor=call_color, edgecolor='k'),
                    Patch(facecolor=setjmp_color, edgecolor='k'),
                    Patch(facecolor=fcontext_color, edgecolor='k'),
                    Patch(facecolor=custom_color, edgecolor='k')]
    custom_labels = ['baseline',
                     'setjmp',
                     'fcontext',
                     'custom']
    plt.legend(custom_lines, custom_labels)

    fig = plt.gcf()
    fig.set_size_inches(5, 5)
    fig.set_dpi(300)
    # bounds = Bbox.from_bounds(-0.1, -0.1, 4.75, 4.6)

    fig.savefig(name + '.pgf')
    fig.savefig(name + '.png')


plot_data(dataX86, "plots/context_switch_x86_64")
plot_data(dataARM32, "plots/context_switch_arm32")
