#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

def edit(_self, req):
    req.perm.assert_permission('ENQUETE_EDIT')
    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('enquete_id')
    question_id =''

    if actionName:
        #設問の削除
        if actionName=='delete':
            question_id = req.args.get('question_id')
            try:
                cursor.execute("""delete from question where enquete_id = %d and question_id=%d"""  % (int(enquete_id),int(question_id)))
            except Exception,e:
                _self.log.debug('%s' % e)
                raise e

    #設問一覧検索
    title = ""
    try:
        sql = ("""SELECT title FROM enquete where enquete_id = %d""" % (int(enquete_id)))
        cursor.execute(sql)
        row = cursor.fetchone()
        title = row[0]

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

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

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

    cursor.close()
    db.commit()

    data = {'question_list': question_list,"enquete_id" : enquete_id,"title":title}

    return 'edit.html', data, None


def edit_detail(_self, req):
    data = {}
    question = {}
    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('enquete_id')
    if actionName:
        #設問の編集
        if actionName=='edit':
            question_id = req.args.get('question_id')
            try:
                cursor.execute("""SELECT enquete_id, question_id, question_title, type, detail FROM question where enquete_id = %d and question_id=%d"""  % (int(enquete_id),int(question_id)))
                row = cursor.fetchone()
            except Exception,e:
                _self.log.debug('%s' % e)
                raise e

            question = {'question_id':row[1], 'question_title':row[2], 'type':row[3], 'detail':row[4]}

        #設問の更新
        elif actionName=='update':
            question_id = req.args.get('question_id')
            question_title = req.args.get('question_title')
            type = req.args.get('type')
            detail = req.args.get('detail')

            try:
                if question_id:
                    cursor.execute("""update question set question_title='%s',type=%d,detail='%s' where enquete_id = %d and question_id=%d"""  % (question_title ,int(type), detail, int(enquete_id),int(question_id)))
                else:
                    when = datetime.now(utc)
                    when_ts = to_timestamp(when)
                    cursor.execute("""insert into question values(%d,%d,'%s',%d,'%s')"""  % (int(enquete_id) , when_ts, question_title, int(type), detail))
            except Exception,e:
                _self.log.debug('%s' % e)
                raise e
        else:
            question = {'question_id':'', 'question_title':'', 'type':'1', 'detail':''}
    else:
        question = {'question_id':'', 'question_title':'', 'type':'1', 'detail':''}

    cursor.close()
    db.commit()

    if actionName:
        if actionName=='update':
            req.redirect(_self.env.href.enquete('edit',{'enquete_id':enquete_id}))

    data = {'question': question,"enquete_id" : enquete_id}

    return 'editdetail.html', data, None
