# Copyright (C) 2005 Aaron Bentley
# <aaron.bentley@utoronto.ca>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
from bzrtools import short_committer
from dotgraph import Node, dot_output, invoke_dot, invoke_dot_aa, NoDot, NoRsvg
from dotgraph import RSVG_OUTPUT_TYPES, DOT_OUTPUT_TYPES, Edge, invoke_dot_html
from bzrlib.branch import Branch
from bzrlib.errors import BzrCommandError, NoCommonRoot, NoSuchRevision
from bzrlib.graph import node_distances, select_farthest
from bzrlib.revision import combined_graph, revision_graph
from bzrlib.revision import MultipleRevisionSources
import bzrlib.errors
import re
import os.path
import time

mail_map = {'aaron.bentley@utoronto.ca'     : 'Aaron Bentley',
            'abentley@panoramicfeedback.com': 'Aaron Bentley',
            'abentley@lappy'                : 'Aaron Bentley',
            'john@arbash-meinel.com'        : 'John Arbash Meinel',
            'mbp@sourcefrog.net'            : 'Martin Pool',
            'robertc@robertcollins.net'     : 'Robert Collins',
            }

committer_alias = {'abentley': 'Aaron Bentley'}
def can_skip(rev_id, descendants, ancestors):
    if rev_id not in descendants:
        return False
    elif rev_id not in ancestors:
        return False
    elif len(ancestors[rev_id]) != 1:
        return False
    elif len(descendants[list(ancestors[rev_id])[0]]) != 1:
        return False
    elif len(descendants[rev_id]) != 1:
        return False
    else:
        return True

def compact_ancestors(descendants, ancestors, exceptions=()):
    new_ancestors={}
    skip = set()
    for me, my_parents in ancestors.iteritems():
        if me in skip:
            continue
        new_ancestors[me] = {} 
        for parent in my_parents:
            new_parent = parent 
            distance = 0
            while can_skip(new_parent, descendants, ancestors):
                if new_parent in exceptions:
                    break
                skip.add(new_parent)
                if new_parent in new_ancestors:
                    del new_ancestors[new_parent]
                new_parent = list(ancestors[new_parent])[0]
                distance += 1
            new_ancestors[me][new_parent] = distance
    return new_ancestors    

def get_rev_info(rev_id, source):
    """Return the committer, message, and date of a revision."""
    committer = None
    message = None
    date = None
    if rev_id == 'null:':
        return None, 'Null Revision', None
    try:
        rev = source.get_revision(rev_id)
    except NoSuchRevision:
        try:
            committer = '-'.join(rev_id.split('-')[:-2]).strip(' ')
            if committer == '':
                return None, None, None
        except ValueError:
            return None, None, None
    else:
        committer = short_committer(rev.committer)
        if rev.message is not None:
            message = rev.message.split('\n')[0]
        gmtime = time.gmtime(rev.timestamp + (rev.timezone or 0))
        date = time.strftime('%Y/%m/%d', gmtime)
    if '@' in committer:
        try:
            committer = mail_map[committer]
        except KeyError:
            pass
    try:
        committer = committer_alias[committer]
    except KeyError:
        pass
    return committer, message, date

class Grapher(object):
    def __init__(self, branch, other_branch=None):
        object.__init__(self)
        self.branch = branch
        self.other_branch = other_branch
        revision_a = self.branch.last_revision()
        if other_branch is not None:
            branch.fetch(other_branch)
            revision_b = self.other_branch.last_revision()
            try:
                self.root, self.ancestors, self.descendants, self.common = \
                    combined_graph(revision_a, revision_b,
                                   self.branch.repository)
            except bzrlib.errors.NoCommonRoot:
                raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
        else:
            self.root, self.ancestors, self.descendants = \
                revision_graph(revision_a, branch.repository)
            self.common = []

        self.n_history = branch.revision_history()
        self.distances = node_distances(self.descendants, self.ancestors, 
                                        self.root)
        if other_branch is not None:
            self.base = select_farthest(self.distances, self.common)
            self.m_history = other_branch.revision_history() 
        else:
            self.base = None
            self.m_history = []

    def dot_node(self, node, num):
        try:
            n_rev = self.n_history.index(node) + 1
        except ValueError:
            n_rev = None
        try:
            m_rev = self.m_history.index(node) + 1
        except ValueError:
            m_rev = None
        if (n_rev, m_rev) == (None, None):
            name = node[-5:]
            cluster = None
        elif n_rev == m_rev:
            name = "rR%d" % n_rev
        else:
            namelist = []
            for prefix, revno in (('r', n_rev), ('R', m_rev)):
                if revno is not None:
                    namelist.append("%s%d" % (prefix, revno))
            name = ' '.join(namelist)
        if None not in (n_rev, m_rev):
            cluster = "common_history"
            color = "#ff9900"
        elif (None, None) == (n_rev, m_rev):
            cluster = None
            if node in self.common:
                color = "#6699ff"
            else:
                color = "white"
        elif n_rev is not None:
            cluster = "my_history"
            color = "#ffff00"
        else:
            assert m_rev is not None
            cluster = "other_history"
            color = "#ff0000"
        if node == self.base:
            color = "#33ff99"

        label = [name]
        committer, message, date = get_rev_info(node, self.branch.repository)
        if committer is not None:
            label.append(committer)

        if date is not None:
            label.append(date)

        if node in self.distances:
            rank = self.distances[node]
            label.append('d%d' % self.distances[node])
        else:
            rank = None

        d_node = Node("n%d" % num, color=color, label="\\n".join(label), 
                    rev_id=node, cluster=cluster, message=message,
                    date=date)
        d_node.rank = rank

        if node not in self.ancestors:
            d_node.node_style.append('dotted')

        return d_node
        
    def get_relations(self, collapse=False):
        dot_nodes = {}
        node_relations = []
        num = 0
        if collapse:
            visible_ancestors = compact_ancestors(self.descendants, 
                                                  self.ancestors, (self.base,))
        else:
            visible_ancestors = self.ancestors
        for node, parents in visible_ancestors.iteritems():
            if node not in dot_nodes:
                dot_nodes[node] = self.dot_node(node, num)
                num += 1
            if visible_ancestors is self.ancestors:
                parent_iter = ((f, 0) for f in parents)
            else:
                parent_iter = (f for f in parents.iteritems())
            for parent, skipped in parent_iter:
                if parent not in dot_nodes:
                    dot_nodes[parent] = self.dot_node(parent, num)
                    num += 1
                edge = Edge(dot_nodes[parent], dot_nodes[node])
                if skipped != 0:
                    edge.label = "%d" % skipped
                node_relations.append(edge)
        return node_relations


def write_ancestry_file(branch, filename, collapse=True, antialias=True,
                        merge_branch=None, ranking="forced"):
    b = Branch.open_containing(branch)[0]
    if merge_branch is not None:
        m = Branch.open_containing(merge_branch)[0]
    else:
        m = None
    b.lock_write()
    try:
        if m is not None:
            m.lock_read()
        try:
            grapher = Grapher(b, m)
            relations = grapher.get_relations(collapse)
        finally:
            if m is not None:
                m.unlock()
    finally:
        b.unlock()

    ext = filename.split('.')[-1]
    output = dot_output(relations, ranking)
    done = False
    if ext not in RSVG_OUTPUT_TYPES:
        antialias = False
    if antialias: 
        output = list(output)
        try:
            invoke_dot_aa(output, filename, ext)
            done = True
        except NoDot, e:
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
                " is installed correctly.")
        except NoRsvg, e:
            print "Not antialiasing because rsvg (from librsvg-bin) is not"\
                " installed."
            antialias = False
    if ext in DOT_OUTPUT_TYPES and not antialias and not done:
        try:
            invoke_dot(output, filename, ext)
            done = True
        except NoDot, e:
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
                " is installed correctly, or use --noantialias")
    elif ext == 'dot' and not done:
        my_file = file(filename, 'wb')
        for fragment in output:
            my_file.write(fragment.encode('utf-8'))
    elif ext == 'html':
        try:
            invoke_dot_html(output, filename)
        except NoDot, e:
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
                " is installed correctly, or use --noantialias")
    elif not done:
        print "Unknown file extension: %s" % ext

