#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')

    enquete_id = req.args.get('enquete_id')
    question_id = req.args.get('question_id')
    group_id = req.args.get('group_id')
    ans = req.args.get('answer')

    answer_list=[]
    group_answer_list=None
    chart = ''
    try:

#        sql = """SELECT ad.question_id as question_id, q.type as type, ad.answer as answer,count(answer) as cnt FROM"""
#        if group_id:
#            sql = sql + " (select ad2.enquete_id as enquete_id,ad2.question_id as question_id, ad2.answer as answer from answer_detail ad2 where ad2.user_id in (select ad3.user_id from answer_detail ad3 where ad3.enquete_id=%d and ad3.question_id=%d and answer='%s')) ad"  % (int(enquete_id),int(group_id),ans)
#        else:
#            sql = sql + " answer_detail ad"
#        sql = sql + (""" inner join question q on ad.question_id = q.question_id where ad.enquete_id = %d and ad.question_id = %d""" % (int(enquete_id),int(question_id)))
#        sql = sql + (""" group by answer order by cnt desc""")
#        _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)
        answer_list = _getAnswerList(_self,enquete_id,question_id,None,None)
        if group_id:
            group_answer_list = _getAnswerList(_self,enquete_id,question_id,group_id,ans)

        #Chart
        if group_id:
            chart = _getChart(group_answer_list,question_id, answer_list)
        else:
            chart = _getChart(answer_list,question_id, None)

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

    req.send_response(200)
    req.send_header('Content-Type', 'text/plain')
    req.send_header('Content-Length', len(chart.encode('utf-8')))
    req.end_headers()
    req.write(chart.encode('utf-8'))


def _getAnswerList(_self,enquete_id,question_id,group_id,ans):
    db = _self.env.get_db_cnx()
    cursor = db.cursor()
    answer_list=[]
    chart = ''
    try:

        sql = """SELECT ad.question_id as question_id, q.type as type, ad.answer as answer,count(answer) as cnt FROM"""
        if group_id:
            sql = sql + " (select ad2.enquete_id as enquete_id,ad2.question_id as question_id, ad2.answer as answer from answer_detail ad2 where ad2.user_id in (select ad3.user_id from answer_detail ad3 where ad3.enquete_id=%d and ad3.question_id=%d and answer='%s')) ad"  % (int(enquete_id),int(group_id),ans)
        else:
            sql = sql + " answer_detail ad"
        sql = sql + (""" inner join question q on ad.question_id = q.question_id where ad.enquete_id = %d and ad.question_id = %d""" % (int(enquete_id),int(question_id)))
        sql = sql + (""" group by answer order by cnt desc""")
        _self.log.debug('%s' % sql)
        cursor.execute(sql)
        for question_id, type, answer, cnt in cursor:
            if answer == "None":
                answer = "未回答"
            _answer = {'question_id':question_id, 'type':type, 'answer':answer, 'count':cnt}
            answer_list.append(_answer)
    except Exception,e:
        _self.log.debug('%s' % e)
        raise e

    return answer_list

def _getChart(anslist,q_id,base_list):

    if anslist:
        g = graph()

        values = []
        labels = []
        y_max = 0
        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

        y_max = max(values) + 1

        if base_list != None:
            base_values = []
            for base_ans in base_list:
                base_values.append(base_ans['count'])
            y_max = max(base_values) + 1

        g.bg = '#ffffff'
        if int(type) == 3:
            idx = 0
            g.bar( 50, '#1fAAFF', '', 20 )
            g.set_data(values)
            g.set_y_max( y_max )
            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 )
            if base_list:
                _color_list = []
                for ans in anslist:
                    idx2 = 0
                    for ans2 in base_list:
                        if ans['answer'] == ans2['answer']:
                            _color_list.append(color_list[idx2])
                            break
                        idx2 = idx2 + 1
                g.pie_slice_colours( _color_list )
            else:
                g.pie_slice_colours( color_list )

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

        return g.render()
    else:
        return None

