#!-*- coding:utf-8 -*-"

import pkg_resources

from decimal import Decimal

from trac.core import *
from trac.util.translation import _
from trac.web.api import IRequestHandler
from trac.web.api import ITemplateStreamFilter
from trac.web.chrome import ITemplateProvider
from trac.web.chrome import add_ctxtnav
from trac.web.chrome import add_link 
from trac.web.chrome import add_script
from trac.web.chrome import add_stylesheet

# local imports
from dbutils import *
from dateutils import *

class TracWorkTimeBurndownChartModule(Component):
    implements(IRequestHandler)

    ### methods for IRequestHandler
    def match_request(self, req):
        path = req.path_info.rstrip('/')
        if path.startswith('/worktime/burndown'):
            return True
        else:
            return False

    def process_request(self, req):
        req.perm.assert_permission('WORKTIME_BURNDOWN_VIEW')
        
        add_ctxtnav(req, u'作業時間入力', href=req.href.worktime())
        from report import TracWorkTimeReportModule
        if self.env.is_component_enabled(TracWorkTimeReportModule):
            add_ctxtnav(req, u'レポート', href=req.href.worktime('report')) 
        add_ctxtnav(req, u'Burndown Chart')
        
        return self._process_burndown(req)

    def _process_burndown(self, req):
        data = {}
        
        from_date = handle_current_date(req,
                                        year_key='from_year',
                                        month_key='from_month')
        to_date = handle_current_date(req,
                                      year_key='to_year',
                                      month_key='to_month')
        
        est_sums = get_daily_estimated_hours(self.env,
                                             from_date=from_date,
                                             to_date=to_date)
        worktime_sums = get_worktime_sum_daily(self.env,
                                               from_date=from_date,
                                               to_date=to_date)
        
        dates = (est_sums.keys() + worktime_sums.keys())
        dates.sort()
        dates = sorted(set(dates), key=dates.index)

        table = []
        
        remain = None
        before_est_sum = Decimal(0)
        worked_ruiseki = Decimal(0)
        for date in dates:
            before_est_sum = est_sum = est_sums.get(date, before_est_sum)
            work_sum = worktime_sums.get(date, Decimal(0))
            worked_ruiseki += work_sum
            remain = est_sum - worked_ruiseki
            table.append((date, est_sum, work_sum, remain))

        data['table'] = table
        data['from_date'] = from_date
        data['to_date'] = to_date
        
        return 'worktime_burndown.html', data, None

