# -*- coding: utf-8 -*-
#  Copyright 2011 Takeshi KOMIYA
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
from docutils import nodes
from docutils.parsers import rst
from seqdiag import parser
from seqdiag.builder import ScreenNodeBuilder
from seqdiag.drawer import DiagramDraw
from seqdiag.utils.rst.nodes import seqdiag
from blockdiag.utils.rst import directives


directive_options_default = dict(format='PNG',
                                 antialias=False,
                                 fontpath=None,
                                 outputdir=None,
                                 nodoctype=False,
                                 noviewbox=False,
                                 inline_svg=False)
directive_options = {}


class SeqdiagDirectiveBase(directives.BlockdiagDirectiveBase):
    """ Directive to insert arbitrary dot markup. """
    name = "seqdiag"
    node_class = seqdiag


class SeqdiagDirective(directives.BlockdiagDirective):
    name = "seqdiag"
    node_class = seqdiag

    @property
    def global_options(self):
        return directive_options

    def node2diagram(self, node):
        tree = parser.parse_string(node['code'])
        return ScreenNodeBuilder.build(tree)

    def node2image(self, node, diagram):
        options = node['options']
        filename = self.image_filename(node)
        fontmap = self.create_fontmap()
        _format = self.global_options['format'].lower()

        if _format == 'svg' and self.global_options['inline_svg'] is True:
            filename = None

        kwargs = dict(self.global_options)
        del kwargs['format']
        drawer = DiagramDraw(_format, diagram, filename,
                             fontmap=fontmap, **kwargs)

        if filename is None or not os.path.isfile(filename):
            drawer.draw()
            content = drawer.save(None)

            if _format == 'svg' and self.global_options['inline_svg'] is True:
                size = drawer.pagesize()
                if 'maxwidth' in options and options['maxwidth'] < size[0]:
                    ratio = float(options['maxwidth']) / size[0]
                    new_size = (options['maxwidth'], int(size[1] * ratio))
                    content = drawer.save(new_size)

                return nodes.raw('', content, format='html')

        size = drawer.pagesize()
        if 'maxwidth' in options and options['maxwidth'] < size[0]:
            ratio = float(options['maxwidth']) / size[0]
            thumb_size = (options['maxwidth'], size[1] * ratio)

            thumb_filename = self.image_filename(node, prefix='_thumb')
            if not os.path.isfile(thumb_filename):
                drawer.filename = thumb_filename
                drawer.draw()
                drawer.save(thumb_size)

            image = nodes.image(uri=thumb_filename, target=filename)
        else:
            image = nodes.image(uri=filename)

        if node['alt']:
            image['alt'] = node['alt']

        return image


def setup(**kwargs):
    for key, value in directive_options_default.items():
        directive_options[key] = kwargs.get(key, value)

    rst.directives.register_directive("seqdiag", SeqdiagDirective)
