# -*- coding: utf-8 -*-
# FormAutoSavePluginPlugin
import re
import logging

from genshi.filters import Transformer

from trac.core import *
from trac.config import Option, BoolOption,  Configuration
from trac.web.chrome import ITemplateProvider, add_stylesheet, add_script
from trac.web.api import IRequestFilter, IRequestHandler
from trac.ticket.report import ReportModule
from trac.util import escape, Markup
from trac.wiki import Formatter
from trac.perm import IPermissionRequestor

from pkg_resources import resource_filename


class FormAutoSavePlugin(Component):
    u"""Formの入力内容を自動的にCookieに保存し、あとで復元できるようにするPluginです。"""

    implements( IRequestHandler ,ITemplateProvider ,IRequestFilter )

    interval = Option( 'formautosave', 'interval', '5000',
            u"""Formを自動保存する間隔を指定します。""")

    # ITemplateProvider methods

    def get_templates_dirs(self):
        yield resource_filename(__name__, 'templates')

    def get_htdocs_dirs(self):
        yield 'formautosave', resource_filename(__name__, 'htdocs')

    # IRequestHandler methods

    def match_request(self, req):
        return re.match(r'^/FormAutoSavePlugin(?:(.*))', req.path_info) is not None

    def process_request(self, req):

        if re.match(r'^/FormAutoSavePlugin/formautosave.js',req.path_info) :
            req.send_response(200)
            req.send_header('Content-Type', 'text/javascript')
            req.end_headers()
            result="""
$(function(){
  $('form' + '#edit, #edit_report, #propertyform').append("<a href='#' class='autosave_restore' style='{font-size:x-small'>Cookieから復元</a>");
  $('form *').autosave({
      'interval': %s
  });
});""" % self.interval
            req.write(result)

    # IRequestFilter methods
    def post_process_request(self, req, template, data, content_type):
        if not re.match(r'^formautosave/jquery.cookie.js',req.path_info) :
            add_script(req, 'formautosave/jquery.cookie.js')
        if not re.match(r'^formautosave/jquery.autosave.pack.js',req.path_info) :
            add_script(req, 'formautosave/jquery.autosave.pack.js')
        if not re.match(r'^/FormAutoSavePlugin/formautosave.js',req.path_info) :
            add_script(req, '/FormAutoSavePlugin/formautosave.js')

        return template, data, content_type

    def pre_process_request(self, req, handler):
        return handler

