import locale
import numpy as np
import matplotlib
from matplotlib.font_manager import FontProperties
from matplotlib import dates

import psycopg2

from config.settings import *
from settings import *
import util.db
import reports.times
from util.log import log

matplotlib.use('Agg')
    
def ram_usage():
    
    import matplotlib.pyplot as plot
    
    db = util.db.connect()
    
    cur = db.cursor()
    
    cur.execute("""
        SELECT measurement_time, free_pct, cach_pct, used_pct
            FROM memory_used() 
            WHERE measurement_time BETWEEN %(start_time)s AND %(end_time)s
            ORDER BY measurement_time
        """, reports.times.sar_range())
    
    results = cur.fetchall()

    if not results:
        no_file = REPORT_DIR_PATH + '/ram_usage.txt'
        with open(no_file, 'w') as no_results:
            no_results.write("No results.")
        no_results.close()
        log('No connections recorded; skipping ram_usage report')
        return
    
    timeseries = [r[0] for r in results]
    memory_free = [float(r[1]) for r in results]
    memory_cached = [float(r[2]) for r in results]
    memory_used = [float(r[3]) for r in results]
    
    y = np.row_stack((memory_free, memory_cached, memory_used, ))
    y_stack = np.cumsum(y, axis=0)
    
    fig = plot.figure(figsize=DEFAULT_FIGURE_SIZE)
    ax = fig.add_subplot(111, axisbg='#fafafa', alpha=0.9)

    hfmt = dates.DateFormatter('%H:%M:%S')
    ax.xaxis.set_major_formatter(hfmt)
    small_font = FontProperties()
    small_font.set_size('small')
    
    ax.set_title('RAM Usage')
    
    ax.set_ylabel('Percent of Total RAM')
    ax.set_ylim(ymin=0, ymax=105)
    
    ax.set_xlim(xmin=reports.times.sar_start(), xmax=reports.times.sar_end())

    ax.fill_between(timeseries, 0, y_stack[0,:], linewidth=0, color='green')
    ax.fill_between(timeseries, y_stack[0,:], y_stack[1,:], linewidth=0, color='#d0efd0')
    ax.fill_between(timeseries, y_stack[1,:], y_stack[2,:], linewidth=0, color='red')
    
    free = matplotlib.patches.Rectangle((0, 0), 1, 1, color='red')
    used = matplotlib.patches.Rectangle((0, 0), 1, 1, color='#d0efd0')
    cach = matplotlib.patches.Rectangle((0, 0), 1, 1, color='green')
    
    lgnd = ax.legend((free, used, cach), ('Used', 'Cached', 'Free',), 
        loc='upper right', bbox_to_anchor=(1.25, 1.0), prop=small_font )
    
    ax.grid(True)
    
    fig.autofmt_xdate()
    
    plot.savefig(REPORT_DIR_PATH + '/ram_usage.pdf', bbox_inches='tight', pad_inches=0.25, bbox_extra_artists=[lgnd])

    plot.close()


def swap_usage():
    
    import matplotlib.pyplot as plot
    
    db = util.db.connect()
    
    cur = db.cursor()
    
    cur.execute("""
        SELECT swap.measurement_time AS measurement_time,
               swap.kbswpused / 1024 AS used_swap_mb,
               (swap.kbswpused + swap.kbswpfree) / 1024 AS total_swap_mb
            FROM swap_used() AS swap
            WHERE swap.measurement_time BETWEEN %(start_time)s AND %(end_time)s
        """, reports.times.sar_range())
    
    results = cur.fetchall()

    if not results:
        no_file = REPORT_DIR_PATH + '/swap_usage.txt'
        with open(no_file, 'w') as no_results:
            no_results.write("No results.")
        no_results.close()
        log('No swap data recorded; skipping swap_usage report')
        return
    
    timeseries = [r[0] for r in results]
    swap_used = [float(r[1]) for r in results]
    total_swap = results[0][2]
    
    fig = plot.figure(figsize=DEFAULT_FIGURE_SIZE)
    ax = fig.add_subplot(111, axisbg='#fafafa', alpha=0.9)

    hfmt = dates.DateFormatter('%H:%M:%S')
    ax.xaxis.set_major_formatter(hfmt)
    ax.set_xlim(xmin=reports.times.sar_start(), xmax=reports.times.sar_end())

    ax.plot(timeseries, swap_used)
    
    small_font = FontProperties()
    small_font.set_size('small')

    ax.set_title('Swap Usage (Total Swap = {ts} MB)'.format(
        ts=locale.format("%d", total_swap, grouping=True)))
    
    ax.set_ylabel('Swap Used (MB)')
    
    ax.grid(True)
    
    fig.autofmt_xdate()
    
    plot.savefig(REPORT_DIR_PATH + '/swap_usage.pdf')

    plot.close()
