#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:
                sql = "delete from question where enquete_id = %s and question_id=%s"
                _self.log.debug('%s' % sql)
                cursor.execute(sql, (int(enquete_id),int(question_id)))
            except Exception,e:
                _self.log.debug('%s' % e)
                raise e
        elif actionName =='savesort':
            listorder = req.args.get('listorder').splitlines()
            for idx, question_id in enumerate(listorder):
                sql = "update question set sort_no=%s where enquete_id=%s and question_id=%s "
                _self.log.debug('%s' % sql)
                cursor.execute(sql, (idx, enquete_id, question_id))
            db.commit()
            message = '並び順を保存しました。'
    #設問一覧検索
    title = ""
    try:
        sql = "SELECT title FROM enquete where enquete_id = %s"
        _self.log.debug('%s' % sql)
        cursor.execute(sql, (int(enquete_id),))
        row = cursor.fetchone()
        title = row[0]

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

    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)

    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:
                sql = "SELECT enquete_id, question_id, question_title, type, detail FROM question where enquete_id = %s and question_id=%s"
                _self.log.debug('%s' % sql)
                cursor.execute(sql, (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:
                    sql = "update question set question_title=%s,type=%s,detail=%s where enquete_id = %s and question_id=%s"
                    _self.log.debug('%s' % sql)
                    cursor.execute(sql, (question_title ,int(type), detail, int(enquete_id),int(question_id)))
                else:
                    when = datetime.now(utc)
                    when_ts = to_timestamp(when)
                    sql = """insert into question values(%s,%s,%s,%s,%s,%s)"""
                    _self.log.debug('%s' % sql)
                    cursor.execute(sql, (int(enquete_id) , when_ts, question_title, int(type), detail, 0))
            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':''}

    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
