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'] = milestone.description
    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, chrome, projects):
        milestones = []
        stats = []
        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')
            stat = calc_ticket_stats(tickets)
            stats.append({'stats': stat})
            m['queries'] = {}
            for k, v in get_query_links(env, milestone_name).items():
                m['queries'][k] = v
            m['tickets'] = tickets # for the iCalendar view
            idx += 1

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

        data = {
            'milestones': milestones,
            'milestone_stats': stats
        }

        data["chrome.nav.mainnav.roadmap.active"] = 1
        data['title'] = _('Roadmap')
        template_dir = os.path.dirname(__file__) + '/templates/'
        chrome.populate_data(req, data)
        output = chrome.render_template(req, template_dir + "roadmap.html", data)
        req.session.save()
        req.send(output, 'text/html')

