#encoding=utf-8
import re
import calendar, time
from datetime import datetime, date, timedelta
from trac.util.datefmt import utc, utcmax, to_timestamp


from genshi.builder import tag

from trac.core import *
from trac.web.chrome import add_stylesheet
from OpenFlashChart import *

def chart(_self, req):
    data = {}
    db = _self.env.get_db_cnx()

    add_stylesheet(req, 'enquete/css/enquete.css')

    cursor = db.cursor()
    enquete_id = req.args.get('enquete_id')
    question_id = req.args.get('question_id')

    title = ""
    question_list=[]
    answer_list=[]
    answer_map={}
    chart_map={}
    chart = ''
    try:

        sql = ("""SELECT ad.question_id as question_id, q.type as type, ad.answer as answer,count(answer) as cnt FROM answer_detail ad inner join question q on ad.question_id = q.question_id where ad.enquete_id = %d and ad.question_id = %d group by answer order by cnt desc""" % (int(enquete_id),int(question_id)))
        _self.log.debug('%s' % sql)
        cursor.execute(sql)
        for question_id, type, answer, cnt in cursor:
            answer = {'question_id':question_id, 'type':type, 'answer':answer, 'count':cnt}
            answer_list.append(answer)

        #Chart
        chart = _getChart(answer_list,question_id)

    except Exception,e:
        _self.log.debug('%s' % e)
        raise e

    cursor.close()

    req.send_response(200)
    req.send_header('Content-Type', 'text/plain')
    req.end_headers()
    req.write(chart)


def _getChart(anslist,q_id):

    if anslist:
        g = graph()

        values = []
        labels = []
        total = 0
        color_list = ['#d01f3c','#1fAAFF','#FFa035','#1fd03c','#6a35a0','#FFFF10','#356aa0','#C79810','#98FFC7','#FF1fFF']
        for ans in anslist:
            total = total + int(ans['count'])

        type = ''
        idx = 0
        for ans in anslist:
            if idx == 0:
                type = ans['type']
            values.append(ans['count'])

            if int(type) == 3:
                lbl = ("""%s""") % (ans['answer'])
            else:
                lbl = ("""%s:%3.1f""") % (ans['answer'],int(ans['count'])*100.0/total)
            labels.append(lbl)
            idx = idx + 1

        g.bg = '#ffffff'
        if int(type) == 3:
            idx = 0
            g.bar( 50, '#1fAAFF', '', 20 )
            g.set_data(values)
            g.set_y_max( max(values) + 1 )
            g.set_x_max( len(anslist) )
            g.set_x_labels(labels)
            g.y_label_steps( 1 )

        else:
            g.pie_chart(60,'#ffffff','#000000',True,1)
            g.pie_data( values, labels )
            g.pie_slice_colours( color_list )
        g.set_tool_tip( '#val#%' )

        g.title( ' ', '{font-size:12px; color: #d01f3c}' )

        return g.render()
    else:
        return None

