#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
Creates the bar charts

All steps required to generate bar charts that use stock (time-agnostic) data.
-----

"""

# Built-in Modules
import itertools
import pickle
import sys
import traceback

# Third-party Modules
# Note the order and structure of matplotlib imports is intentional.
import matplotlib
matplotlib.use('AGG')  # Note: this statement must be run before any other matplotlib imports are done.
import matplotlib.pyplot as plt
import matplotlib.patches as patches

# My modules
import chart_tools

log               = chart_tools.log
payload           = chart_tools.payload
chart_data        = payload['data']
p_dict            = payload['p_dict']
k_dict            = payload['k_dict']
props             = payload['props']
chart_name        = props['name']
plug_dict         = payload['prefs']
annotation_values = []
bar_colors        = []
x_labels          = []
x_ticks           = []

log['Threaddebug'].append(u"chart_bar_stock.py called.")
if plug_dict['verboseLogging']:
    chart_tools.log['Threaddebug'].append(u"{0}".format(payload))

try:

    def __init__():
        pass

    ax = chart_tools.make_chart_figure(width=p_dict['chart_width'], height=p_dict['chart_height'], p_dict=p_dict)

    chart_tools.format_axis_x_ticks(ax=ax, p_dict=p_dict, k_dict=k_dict, logger=log)
    chart_tools.format_axis_y(ax=ax, p_dict=p_dict, k_dict=k_dict, logger=log)

    # ============================  Iterate the Bars  =============================
    for bar in chart_data:
        b_num        = bar['number']
        color        = bar['color_{i}'.format(i=b_num)]
        suppress_bar = p_dict.get('suppressBar{i}'.format(i=b_num), False)
        # x_labels.append(bar['legend_{i}'.format(i=b_num)])
        x_ticks.append(b_num)
        y_val = float(bar['val_{i}'.format(i=b_num)])
        p_dict['data_array'].append(y_val)
        bar_colors.append(color)

        # ====================  Bar and Background Color the Same  ====================
        # If the bar color is the same as the background color, alert the user.
        if color == p_dict['backgroundColor'] and not suppress_bar:
            chart_tools.log['Warning'].append(u"[{name}] Area {i} color is the same as the background color (so "
                                              u"you may not be able to see it).".format(name=chart_name, i=b_num))

        # =============================  Bar Suppressed  ==============================
        # If the bar is suppressed, remind the user they suppressed it.
        if suppress_bar:
            chart_tools.log['Info'].append(u"[{name}] Bar {i} is suppressed by user setting. You can re-enable it in "
                                           u"the device configuration menu.".format(name=chart_name, i=b_num))

        # ============================  Display Zero Bars  ============================
        # Early versions of matplotlib will truncate leading and trailing bars where the value is zero.
        # With this setting, we replace the Y values of zero with a very small positive value
        # (0 becomes 1e-06). We get a slice of the original data for annotations.
        # annotation_values.append(y_val)
        annotation_values.append(bar['val_{i}'.format(i=b_num)])
        if p_dict.get('showZeroBars', False):
            if y_val == 0:
                y_val = 1e-06

        # ================================  Bar Width  ================================
        try:
            bar_width = float(p_dict['barWidth'])
            if bar_width == 0:
                width = 0.8
            else:
                width = float(p_dict['barWidth'])
        except ValueError:
            width = 0.8
            chart_tools.log['Warning'].append(u"[{n}] Problem setting bar width. Check value "
                                              u"({w}).".format(n=chart_name, w=p_dict['barWidth']))

        # ==============================  Plot the Bar  ===============================
        # Plot the bars. If 'suppressBar{thing} is True, we skip it.
        if not suppress_bar:
            ax.bar(b_num,
                   y_val,
                   width=float(p_dict['barWidth']),