#encoding=utf-8
import re
import calendar, time
import urllib
import md5


from datetime import datetime, date, timedelta
from trac.util.datefmt import utc, utcmax, to_timestamp

from genshi.core import *
from genshi.builder import tag

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

def answer(_self, req):
    req.perm.assert_permission('ENQUETE_VIEW')
    data = {}
    db = _self.env.get_db_cnx()

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

    actionName = req.args.get('actionName')
    when = datetime.now(utc)
    when_ts = to_timestamp(when)

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

    user_id = ''

    #anonymousの場合はタイムスタンプを付加
    if req.authname == 'anonymous':
        user_id = ("%s_%d") % (req.authname , when_ts)
    else:
        user_id = req.authname

    #ユーザをdigest化し、判りにくくする
    digest_user = md5.new(user_id).hexdigest()
    if actionName:
        #回答送信
        if actionName=='send':
            req.perm.assert_permission('ENQUETE_ANSWER')
            when = datetime.now(utc)
            when_ts = to_timestamp(when)
            try:
                sql = [
                       ("""delete from answer where enquete_id = %d and user_id='%s'""" )  % (int(enquete_id),digest_user),
                       ("""delete from answer_detail where enquete_id = %d and user_id='%s'""" ) % (int(enquete_id),digest_user),
                       ("""insert into answer values( %d, '%s' , %d, '%s')""") % (int(enquete_id),digest_user, 0, when)
                       ]
                for s in sql:
                    try:
                        _self.log.debug('%s' % s)
                        cursor.execute(s)
                    except Exception,e:
                        _self.log.debug('%s' % e)
                        None

                question_id = req.args.get('question_id')
                count = 0
                for q in question_id:
                    answer = req.args.get('answer_'+str(count))
                    q_id =''
                    if isinstance(question_id,list):
                        q_id = question_id[count]
                    else:
                        q_id = question_id

                    if isinstance(answer,list):
                        for ans in answer:
                            sql = ("""insert into answer_detail values( %d,'%s',%d,'%s')""" % (int(enquete_id),digest_user,int(q_id),ans))
                            _self.log.debug('%s' % sql)
                            cursor.execute(sql)
                    else:
                        sql = ("""insert into answer_detail values( %d,'%s',%d,'%s')""" % (int(enquete_id),digest_user,int(q_id),answer))
                        _self.log.debug('%s' % sql)
                        cursor.execute(sql)

                    count = count + 1
            except Exception,e:
                db.rollback()
                _self.log.debug('%s' % e)
                raise e

            db.commit()

            #req.redirect(_self.env.href.enquete())
            return "thanks.html", data, None

    #回答一覧
    title = ""
    status = ""
    question_list=[]
    answer_list=[]
    answer_map={}
    chart_map={}
    group_id = req.args.get('group_id');
    try:
        sql = ("""SELECT title,status FROM enquete where enquete_id = %d""" % (int(enquete_id)))
        _self.log.debug('%s' % sql)
        cursor.execute(sql)
        row = cursor.fetchone()
        title = row[0]
        status = row[1]

        sql = ("""SELECT enquete_id, question_id, question_title, type, detail FROM question where enquete_id = %d""" % (int(enquete_id)))
        _self.log.debug('%s' % sql)
        cursor.execute(sql)

        for enquete_id,question_id, question_title, type, detail in cursor:
            question = {'enquete_id':enquete_id, 'question_id':question_id, 'question_title':question_title, 'type':type, 'detail':detail}
            question_list.append(question)

        if actionName:
            #アンケート集計
            if actionName=='count' or actionName=='group':
                # アンケート結果
                sql = ("""SELECT enquete_id, question_id, answer ,count(answer) as cnt FROM answer_detail where enquete_id = %d group by question_id,answer order by cnt desc""" % (int(enquete_id)))
                _self.log.debug('%s' % sql)
                cursor.execute(sql)
                for enquete_id, question_id, answer, cnt in cursor:
                    al = []
                    if question_id in answer_map:
                        al = answer_map[question_id]
                    ans = {'enquete_id':enquete_id, 'question_id':question_id, 'answer':answer, 'count':cnt}
                    al.append(ans)
                    answer_map[question_id] = al

                #for Pie Chart
                for question in question_list:
                    question_id = question['question_id']
                    if question_id in answer_map:
                        when = datetime.now(utc)
                        when_ts = to_timestamp(when)
                        query = {'enquete_id': enquete_id,'question_id': question_id,'timestamp':when_ts}
                        url = ("""%s?%s""") % (_self.env.href.enquete('chart') ,urllib.urlencode(query))
                        chart_map[question_id] = url


        sql = ("""SELECT question_id, answer FROM answer_detail where enquete_id = %d and user_id='%s'""" % (int(enquete_id), digest_user))
        _self.log.debug('%s' % sql)
        cursor.execute(sql)

        for question_id, answer in cursor:
            answer = {'question_id':question_id, 'answer':answer}
            answer_list.append(answer)

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

    db.commit()

    data = {'question_list': question_list,"enquete_id" : enquete_id,"title":title,'status':status,'answer_list':answer_list,'answer_map':answer_map,'chart_map':chart_map, 'group_id':group_id}

    if actionName:
        if actionName=='count' or  actionName=='group':
            return 'count.html', data, None
        else:
            return 'answer.html', data, None
    else:
        return 'answer.html', data, None


