# Copyright (C) 2004, 2005 Aaron Bentley
# <aaron@aaronbentley.com>
#
#    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 subprocess import Popen, PIPE
import os.path
import errno
import tempfile
import shutil

RSVG_OUTPUT_TYPES = ('png', 'jpg')
DOT_OUTPUT_TYPES = ('svg', 'svgz', 'gif', 'jpg', 'ps', 'fig', 'mif', 'png',
                    'cmapx')

class NoDot(Exception):
    def __init__(self):
        Exception.__init__(self, "Can't find dot!")

class NoRsvg(Exception):
    def __init__(self):
        Exception.__init__(self, "Can't find rsvg!")

class Node(object):
    def __init__(self, name, color=None, label=None, rev_id=None,
                 cluster=None, node_style=None, date=None, message=None):
        self.name = name
        self.color = color
        self.label = label
        self.committer = None
        self.rev_id = rev_id
        if node_style is None:
            self.node_style = []
        self.cluster = cluster
        self.rank = None
        self.date = date
        self.message = message
        self.href = None

    @staticmethod
    def get_attribute(name, value):
        if value is None:
            return ''
        value = value.replace("\\", "\\\\")
        value = value.replace('"', '\\"')
        value = value.replace('\n', '\\n')
        return '%s="%s"' % (name, value)

    def define(self):
        attributes = []
        style = []
        if self.color is not None:
            attributes.append('fillcolor="%s"' % self.color)
            style.append('filled')
        style.extend(self.node_style)
        if len(style) > 0:
            attributes.append('style="%s"' % ",".join(style))
        label = self.label
        if label is not None:
            attributes.append('label="%s"' % label)
        attributes.append('shape="box"')
        tooltip = None
        if self.message is not None:
            tooltip = self.message
        attributes.append(self.get_attribute('tooltip', tooltip))
        if self.href is not None:
            attributes.append('href="%s"' % self.href)
        elif tooltip:
            attributes.append('href="#"')
        if len(attributes) > 0:
            return '%s[%s]' % (self.name, " ".join(attributes))

    def __str__(self):
        return self.name

class Edge(object):
    def __init__(self, start, end, label=None):
        object.__init__(self)
        self.start = start
        self.end = end
        self.label = label

    def dot(self, do_weight=False):
        attributes = []
        if self.label is not None:
            attributes.append(('label', self.label))
        if do_weight:
            weight = '0'
            if self.start.cluster == self.end.cluster:
                weight = '1'
            elif self.start.rank is None:
                weight = '1'
            elif self.end.rank is None:
                weight = '1'
            attributes.append(('weight', weight))
        if len(attributes) > 0:
            atlist = []
            for key, value in attributes:
                atlist.append("%s=\"%s\"" % (key, value))
            pq = ' '.join(atlist)
            op = "[%s]" % pq
        else:
            op = ""
        return "%s->%s%s;" % (self.start.name, self.end.name, op)

def make_edge(relation):
    if hasattr(relation, 'start') and hasattr(relation, 'end'):
        return relation
    return Edge(relation[0], relation[1])

def dot_output(relations, ranking="forced"):
    defined = {}
    yield "digraph G\n"
    yield "{\n"
    clusters = set()
    edges = [make_edge(f) for f in relations]
    def rel_appropriate(start, end, cluster):
        if cluster is None:
            return (start.cluster is None and end.cluster is None) or \
                start.cluster != end.cluster
        else:
            return start.cluster==cluster and end.cluster==cluster

    for edge in edges:
        if edge.start.cluster is not None:
            clusters.add(edge.start.cluster)
        if edge.end.cluster is not None:
            clusters.add(edge.end.cluster)
    clusters = list(clusters)
    clusters.append(None)
    for index, cluster in enumerate(clusters):
        if cluster is not None and ranking == "cluster":
            yield "subgraph cluster_%s\n" % index
            yield "{\n"
            yield '    label="%s"\n' % cluster
        for edge in edges:
            if edge.start.name not in defined and edge.start.cluster == cluster:
                defined[edge.start.name] = edge.start
                my_def = edge.start.define()
                if my_def is not None:
                    yield "    %s\n" % my_def
            if edge.end.name not in defined and edge.end.cluster == cluster:
                defined[edge.end.name] = edge.end
                my_def = edge.end.define()
                if my_def is not None:
                    yield "    %s;\n" % my_def
            if rel_appropriate(edge.start, edge.end, cluster):
                yield "    %s\n" % edge.dot(do_weight=ranking=="forced")
        if cluster is not None and ranking == "cluster":
            yield "}\n"

    if ranking == "forced":
        ranks = {}
        for node in defined.itervalues():
            if node.rank not in ranks:
                ranks[node.rank] = set()
            ranks[node.rank].add(node.name)
        sorted_ranks = [n for n in ranks.iteritems()]
        sorted_ranks.sort()
        last_rank = None
        for rank, nodes in sorted_ranks:
            if rank is None:
                continue
            yield 'rank%d[style="invis"];\n' % rank
            if last_rank is not None:
                yield 'rank%d -> rank%d[style="invis"];\n' % (last_rank, rank)
            last_rank = rank
        for rank, nodes in ranks.iteritems():
            if rank is None:
                continue
            node_text = "; ".join('"%s"' % n for n in nodes)
            yield ' {rank = same; "rank%d"; %s}\n' % (rank, node_text)
    yield "}\n"

def invoke_dot_aa(input, out_file, file_type='png'):
    """\
    Produce antialiased Dot output, invoking rsvg on an intermediate file.
    rsvg only supports png, jpeg and .ico files."""
    tempdir = tempfile.mkdtemp()
    try:
        temp_file = os.path.join(tempdir, 'temp.svg')
        invoke_dot(input, temp_file, 'svg')
        cmdline = ['rsvg-convert', temp_file, out_file]
        try:
            rsvg_proc = Popen(cmdline)
        except OSError, e:
            if e.errno == errno.ENOENT:
                raise NoRsvg()
        status = rsvg_proc.wait()
    finally:
        shutil.rmtree(tempdir)
    return status

def invoke_dot(input, out_file=None, file_type='svg', antialias=None,
               fontname="Helvetica", fontsize=11):
    cmdline = ['dot', '-T%s' % file_type, '-Nfontname=%s' % fontname,
               '-Efontname=%s' % fontname, '-Nfontsize=%d' % fontsize,
               '-Efontsize=%d' % fontsize]
    if out_file is not None:
        cmdline.extend(('-o', out_file))
    try:
        dot_proc = Popen(cmdline, stdin=PIPE)
    except OSError, e:
        if e.errno == errno.ENOENT:
            raise NoDot()
        else:
            raise
    for line in input:
        dot_proc.stdin.write(line.encode('utf-8'))
    dot_proc.stdin.close()
    return dot_proc.wait()

def invoke_dot_html(input, out_file):
    """\
    Produce an html file, which uses a .png file, and a cmap to provide
    annotated revisions.
    """
    tempdir = tempfile.mkdtemp()
    try:
        temp_dot = os.path.join(tempdir, 'temp.dot')
        status = invoke_dot(input, temp_dot, file_type='dot')

        dot = open(temp_dot)
        temp_file = os.path.join(tempdir, 'temp.cmapx')
        status = invoke_dot(dot, temp_file, 'cmapx')

        png_file = '.'.join(out_file.split('.')[:-1] + ['png'])
        dot.seek(0)
        status = invoke_dot(dot, png_file, 'png')

        png_relative = png_file.split('/')[-1]
        html = open(out_file, 'wb')
        w = html.write
        w('<html><head><title></title></head>\n')
        w('<body>\n')
        w('<img src="%s" usemap="#G" border=0/>' % png_relative)
        w(open(temp_file).read())
        w('</body></html>\n')
    finally:
        shutil.rmtree(tempdir)
    return status

