from trac.core import *
from pkg_resources import resource_filename
from trac.config import Option, IntOption, ListOption, BoolOption
from trac.web.api import IRequestHandler, Href
from trac.util.translation import _
from trac.web.chrome import add_stylesheet, add_script, INavigationContributor, ITemplateProvider
from trac.web.chrome import Chrome
from trac.util.datefmt import utc, to_timestamp, from_utimestamp
from genshi.template import TemplateLoader
from genshi.filters.transform import Transformer
from trac.web.api import ITemplateStreamFilter
from trac.perm import IPermissionRequestor
from trac.util import escape, Markup

import time
from datetime import datetime, timedelta




class DashBoard(Component):
    implements(IRequestHandler, ITemplateProvider, IPermissionRequestor, INavigationContributor)
    
    permission = Option('dashboard', 'permission', '')
    default_milestone = Option('dashboard', 'default_milestone', '')

    def __init__(self):
        self.db = self.env.get_db_cnx()
        self.username = None
        self.backDate = 30
        self.ticket_closed = ['checkedin', 'closed']

        self.ticket_closed_sql = "','".join(self.ticket_closed)

        self.milestone = self.default_milestone
        
        if self.permission:
            self.perm = self.permission
        else:
            self.perm = 'DASHBOARD_VIEW'

        self.env.log.debug("Using Permission: %s" % self.permission)

    
    # INavigationContributor methods
    def get_active_navigation_item(self, req):
        return 'dashboard'

    def get_navigation_items(self, req):
        if self.perm in req.perm or 'TRAC_ADMIN' in req.perm:
            yield 'mainnav', 'dashboard', Markup('<a href="%s">Dashboard</a>' % (
                    self.env.href.dashboard() ) )



    def get_permission_actions(self):
        yield self.perm

   
    # IRequestHandler methods
    def match_request(self, req):
        serve = False
        self.env.log.debug("Match Request")


        uri = req.path_info.lstrip('/').split('/')
        if uri[0] == 'dashboard':
            serve = True

        self.env.log.debug("Handle Request: %s" % serve)
        self.baseURL = req.href('dashboard', '/')
        self.baseQueryURL = req.href('query', '/')
        self.username = req.authname
        if 'milestone' in req.args:
            self.milestone = req.args.get('milestone')
        else:
            self.milestone = self.default_milestone

        if self.milestone == '':
            cursor = self.db.cursor()
            sql = "select name from milestone where (completed = 0) limit 0, 1"
            cursor.execute(sql)
            for name, in cursor:
                self.milestone = name

        if 'dev' in req.args:
            self.username = req.args.get('dev')
        else:
            self.username = req.authname

            return serve

        if not self.perm in req.perm:
            self.env.log.debug("NO Permission to view")
            return False

        return serve
 
    def get_updated_tickets(self):
        cursor = self.db.cursor()
        sql = "select id, component, summary, status from ticket where (owner = '%s') and (changetime >= %s) and (status not in ('%s', 'new')) order by changetime desc" % (self.username, self.stamp, self.ticket_closed_sql)
        cursor.execute(sql)
        out = []
        idx = 0
        for id, component, summary, status in cursor:
            data = {
                '__idx__': idx,
                'id': id,
                'component': component,
                'summary': summary,
                'status': status
            }
            idx = idx + 1
            out.append(data)
        return out

    def get_new_tickets(self):
        cursor = self.db.cursor()
        sql = "select id, status, component, summary, changetime, priority from ticket where (owner = '%s') and (status in ('new', 'assigned')) and (type = 'defect') order by changetime desc" % self.username
        cursor.execute(sql)
        out = []
        idx = 0
        for id, status, component, summary, changetime, priority in cursor:
            data = {
                '__idx__': idx,
                'id': id,
                'status': status,
                'component': component,
                'summary': summary,
                'priority': priority,
                'changetime': from_utimestamp(changetime)
            }
            idx = idx + 1
            out.append(data)
        return out

    def get_closed_tickets(self):
        cursor = self.db.cursor()
        sql = "select id, component, summary, changetime, status from ticket where (owner = '%s') and (status in ('%s')) and (changetime >= %s) order by component, status, changetime desc" % (self.username, self.ticket_closed_sql, self.stamp)
        cursor.execute(sql)
        out = []
        idx = 0
        for id, component, summary, changetime, status in cursor:
            data = {
                '__idx__': idx,
                'id': id,
                'component': component,
                'summary': summary,
                'status': status,
                'changetime': datetime.fromtimestamp(changetime, utc)
            }
            idx = idx + 1
            out.append(data)
        return out

    def get_milestone_tickets(self):
        cursor = self.db.cursor()
        sql = "select id, component, summary, status, priority from ticket where (owner = '%s') and (status not in ('%s', 'new')) and (type in ('defect', 'enhancement')) and (milestone = '%s') order by component, priority" % (self.username, self.ticket_closed_sql, self.milestone)
        cursor.execute(sql)
        out = []
        idx = 0
        for id, component, summary, status, priority in cursor:
            data = {
                '__idx__': idx,
                'id': id,
                'component': component,
                'summary': summary,
                'status': status,
                'priority': priority
            }
            idx = idx + 1
            out.append(data)
        return out

    def get_todo_tickets(self):
        cursor = self.db.cursor()
        sql = "select id, component, summary, status from ticket where (owner = '%s') and (status not in ('%s')) and (type = 'task') order by changetime desc" % (self.username, self.ticket_closed_sql)
        cursor.execute(sql)
        out = []