# -*- coding: utf-8 -*-

from trac.core import *
from trac.admin import IAdminPanelProvider
from trac.web.chrome import ITemplateProvider
from trac.util.translation import _
import re
import pkg_resources

from trac.web.chrome import add_notice, add_warning, Chrome, \
                            ITemplateProvider
from trac.resource import ResourceNotFound
                 
from model import *

from trac.ticket.model import Ticket
from trac.util.datefmt import format_date, to_datetime
                            
class AdminPanel(Component):
    implements(IAdminPanelProvider, ITemplateProvider)

    _type = 'changedaterecord'
    _label = (_('ChangeDateRecord'), _('ChangeDateRecord'))

    # ITemplateProvider methods

    def get_htdocs_dirs(self):
        return []

    def get_templates_dirs(self):
        return [pkg_resources.resource_filename(__name__, 'templates')]
    # IAdminPanelProvider methods

    def get_admin_panels(self, req):
        if 'TICKET_ADMIN' in req.perm:
            yield ('ticket', _('Ticket System'), self._type, self._label[1])

    def render_admin_panel(self, req, cat, page, querychart):
        req.perm.require('TICKET_ADMIN')
        # Detail view?
        data = {}
        if req.method == 'POST':
                
            if req.args.get('reset'):
                
                ticket_ids = req.args.get('ticket_ids')
                condition = None
                if ticket_ids:
                    if ticket_ids.find(':') != -1:
                        range_ids = ticket_ids.split(':')
                        condition = " where id between %d and %d " \
                                    %(int(range_ids[0]), int(range_ids[1]))
                    else:
                        condition = " where id = %d " \
                                    %(int(ticket_ids))
                                
                sql = "SELECT id from ticket"
                if condition:
                    sql += condition
                
                db = self.env.get_db_cnx()
                print sql
                #rebuild_status_log(self.env,1,db)
                cursor = db.cursor()
                cursor.execute(sql)
                ids = [id for id, in cursor]
                for id in ids:
                    #delete_status_log(env,ticket_id,db)
                    status_dt = reset_status(self.env, id, db)
                    ticket = Ticket(self.env, id, db=db)
                    for m in status_dt:
                        ticket[m] = status_dt[m]
                    ticket.save_changes(req.authname, 'Reset from Admin Console.', when=None, db=db, cnum='')
                db.commit()
                
                add_notice(req, "Data has been reseted.\nTicket: %s" %str(ids))
                
        return 'admin_changedaterecord.html', data

