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

from __future__ import unicode_literals
from ascii_graph import Pyasciigraph
import sys
import codecs
from optparse import OptionParser
import re
from ascii_graph.colors import *
from ascii_graph.colordata import hcolor

def input_analyzer(line, data):
    split = split_once_rightmost(line)
    data.append((split[0], float(split[1])))

def split_once_rightmost(s):
     seq = s.split(':')
     if len(seq) > 1:
         return [":".join(seq[0:-1]), seq[-1]]
     return seq

if __name__ == '__main__':
    usage = "usage: %prog [-l <label>] [-f file] [-s inc|dec] \\\n"\
            "   [-c] [-t <first color threshold> [-T <second color threshold>] \\\n"\
            "   [-w <number of char>] [-m <min len of char>] [-H] [-M cs|si]\n\n"\
            "examples:\n"\
            "   printf 'label1:10\\nlabel2:100\\n' | %prog -l 'my graph'\n"\
            "   printf 'label1:1000\\nlabel2:20000\\n' | %prog -l 'my graph' -H -M 'si'\n"\
            "   printf 'l1:10\\nl2:100\\n' > ./mf; %prog -l 'my graph' -f ./mf\n"\
            "   %prog -l 'my graph' -f mf -s inc\n"\
            "   %prog -l 'my graph' -f mf -s dec -w 60 -m 10\n"\
            "   %prog -l 'my graph' -f mf -c\n"\
            "   %prog -l 'my graph' -f mf -c -t 5 -T 50\n"

    parser = OptionParser(usage=usage)
    parser.add_option("-f", "--file", dest="filename", 
            help="import data from FILE (one data per line,            "\
                "format: <label>:<value>)", 
            metavar="FILE")
    parser.add_option("-s", "--sort", dest="sort", 
            help="sort type: inc (increasing) or dec (decreasing)", 
            metavar="SORT")
    parser.add_option("-l", "--label", dest="label", 
            help="label of the graph", 
            metavar="LAB")
    parser.add_option("-w", "--width", dest="width", 
            help="width of the graph", 
            metavar="WIDTH")
    parser.add_option("-m", "--min_graph", dest="mingraph", 
            help="minimum length of the graph bar", 
            metavar="LEN")
    parser.add_option("-t", "--threshold-1", dest="t1",
            help="first color threshold, only make sense if --color is passed", 
            metavar="TC1")
    parser.add_option("-T", "--threshold-2", dest="t2",
            help="second color threshold, only make sense if --color is passed", 
            metavar="TC2")
    parser.add_option("-c", "--color",
            action="store_true", dest="color", default=False,
            help="Color the graph")
    parser.add_option("-H", "--human-readable",
            action="store_true", dest="human_readable", default=False,
            help="enable human readable mode")
    parser.add_option("-M", "--human-readable-mane",
            dest="hr_mode", default='cs',
            help="Human readable mode ('cs' -> power of 1024 or 'si' -> power of 1000, default: cs)")

    (options, args) = parser.parse_args()

    data=[]

    if options.filename:
        try:
            f = open(options.filename, 'r')
        except IOError:
            print('cannot open file: %(file)s' % { 'file': options.filename})
            exit(1)

        if sys.version < '3':
            char_stream = codecs.getreader("utf-8")(f)
        else:
            char_stream = f

        for line in char_stream:
            input_analyzer(line, data)

    if not sys.stdin.isatty():
        if sys.version < '3':
            char_stream = codecs.getreader("utf-8")(sys.stdin)
        else:
            char_stream = sys.stdin
        for line in char_stream:
            input_analyzer(line, data)

    if options.human_readable:
        hr_mode = options.hr_mode
    else:
        hr_mode = None
    label = options.label or ''
    width = options.width or 79
    width = int(width)
    mingraph = options.mingraph or width/2
    mingraph = int(mingraph)
    sort = options.sort or 0
    if sort == 'dec':
        data = sorted(data, key=lambda value: value[1], reverse=True)
    if sort == 'inc':
        data = sorted(data, key=lambda value: value[1], reverse=False)

    graph = Pyasciigraph(line_length=width, min_graph_length=mingraph, multivalue=False, human_readable=hr_mode)

    if options.color:
       maxval = int(max(data, key=lambda item:item[1])[1])
       t1 = float(options.t1) if not options.t1 is None else maxval / 3
       t2 = float(options.t2) if not options.t2 is None else maxval * 2 / 3
       thresholds = {
           t1:     Gre,
           t2:     Yel,
           maxval + 1: Red,
       }
       data = hcolor(data, thresholds)


    counter = 0 
    for line in graph.graph(label, data):
        #skip the first two lines if no label
        if not options.label and counter < 2:
            counter = counter + 1
        else:
            if sys.version < '3':
                print(line.encode('utf-8'))
            else:
                print(line)

