#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 edittitle(_self, req):
    req.perm.assert_permission('ENQUETE_EDIT')
    data = {}
    db = _self.env.get_db_cnx()
    error = ""

    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=='regist':
            try:
                title = req.args.get('newtitle')
                description = req.args.get('description')
                expire_date = req.args.get('expire_date')
                if title:
                    try:
                        sql = ''
                        if enquete_id == '':
                            sql = "insert into enquete values(%s,%s,%s, '',%s,%s,%s,%s)"
                            _self.log.debug('%s' % sql)
                            cursor.execute(sql, (when_ts ,title, 0, when, req.authname , expire_date, description))
                        else:
                            sql = "update enquete set title=%s,expire_date=%s,update_date=%s,description=%s where enquete_id=%s"
                            _self.log.debug('%s' % sql)
                            cursor.execute(sql, (title, expire_date, when , description, enquete_id))
                    except Exception,e:
                        _self.log.debug('%s' % e)
                        raise e

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

            req.redirect(_self.env.href.enquete())

    #設問一覧検索
    title = ""
    expire_date = ""
    description = ""
    try:
        if actionName == 'update':
            sql = "SELECT title,expire_date,description FROM enquete where enquete_id = %s"
            _self.log.debug('%s' % sql)
            cursor.execute(sql,  (int(enquete_id),))
            row = cursor.fetchone()
            title = row[0]
            expire_date = row[1]
            description = row[2]
        elif actionName == 'add':
            enquete_id=""
            title = ""
            expire_date = ""
            description = ""


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

    data = {"enquete_id":enquete_id,"title":title,'expire_date':expire_date,'description':description,'error':error}

    return 'title.html', data, None


