import os

from tram.util import debug
from trac.util import unescape
from trac.web.chrome import add_stylesheet, add_script
from trac.ticket import Milestone
from trac.ticket.roadmap import * 
from trac.util.datefmt import format_datetime, pretty_timedelta
from datetime import datetime, tzinfo, timedelta
from trac.util.translation import _
from trac.wiki.formatter import wiki_to_html

def milestone_cmp(x, y):
    if not x.has_key("due"):
        if not y.has_key("due"):
            return 0
        else:
            return 1
    else:
        if not y.has_key("due"):
            return -1
        else:
            try:
                return x["due"] > y["due"]
            except Exception, e:
                return 0

def milestone_to_hdf(env, db, req, milestone):
    hdf = {'name': milestone.name,
           'href': req.href.milestone(milestone.name)}
    if milestone.description:
        hdf['description_source'] = milestone.description
        hdf['description'] = wiki_to_html(milestone.description, env, req, db)
    if milestone.due:
        hdf['due'] = milestone.due
        hdf['due_date'] = format_date(milestone.due)
        hdf['due_delta'] = pretty_timedelta(milestone.due + timedelta(60))
        hdf['late'] = milestone.is_late
    if milestone.completed:
        hdf['completed'] = milestone.completed
        hdf['completed_date'] = format_datetime(milestone.completed)
        hdf['completed_delta'] = pretty_timedelta(milestone.completed)
    return hdf

def calc_ticket_stats(tickets):
    total_cnt = len(tickets)
    active = [ticket for ticket in tickets if ticket['status'] != 'closed']
    active_cnt = len(active)
    closed_cnt = total_cnt - active_cnt

    percent_active, percent_closed = 0, 0
    if total_cnt > 0:
        percent_active = round(float(active_cnt) / float(total_cnt) * 100)
        percent_closed = round(float(closed_cnt) / float(total_cnt) * 100)
        if percent_active + percent_closed > 100:
            percent_closed -= 1

    return {
        'total_tickets': total_cnt,
        'active_tickets': active_cnt,
        'percent_active': percent_active,
        'closed_tickets': closed_cnt,
        'percent_closed': percent_closed
    }

def get_query_links(req, milestone, grouped_by='component', group=None):
    q = {}
    if not group:
        q['all_tickets'] = req.href.query(milestone=milestone)
        q['active_tickets'] = req.href.query(
            milestone=milestone, status=('new', 'assigned', 'reopened'))
        q['closed_tickets'] = req.href.query(
            milestone=milestone, status='closed')
    else:
        q['all_tickets'] = req.href.query(
            {grouped_by: group}, milestone=milestone)
        q['active_tickets'] = req.href.query(
            {grouped_by: group}, milestone=milestone,
            status=('new', 'assigned', 'reopened'))
        q['closed_tickets'] = req.href.query(
            {grouped_by: group}, milestone=milestone, status='closed')
    return q




class RoadmapModule(object):

   def process_request(self, req, projects):
        milestones = []
        for project in projects:
            env = project["env"]
            for m in Milestone.select(env, False, env.get_db_cnx()):
                req.href = env.href
                milestone = milestone_to_hdf(env, env.get_db_cnx(), req, m)
                milestone['project'] = project
                milestones.append(milestone)

        milestones.sort(milestone_cmp)

        idx = 0
        for m in milestones:
            project = m['project']
            env = project['env']
            milestone_name = unescape(m['name']) # Kludge
            prefix = 'roadmap.milestones.%d.' % idx
            tickets = get_tickets_for_milestone(env, env.get_db_cnx(), milestone_name,
                                                'owner')
            req.hdf[prefix + 'stats'] = calc_ticket_stats(tickets)
            for k, v in get_query_links(env, milestone_name).items():
                req.hdf[prefix + 'queries.' + k] = v
            m['tickets'] = tickets # for the iCalendar view
            idx += 1

            # make milestone names unique
            m["name"] = project["name"] + " " + m["name"]

        req.hdf['roadmap.milestones'] = milestones
        req.hdf["chrome.nav.mainnav.roadmap.active"] = 1
        req.hdf['title'] = _('Roadmap')
        template_dir = os.path.dirname(__file__) + '/templates/'
        req.display(template_dir + "roadmap.cs", 'text/html')

