import drawtetrado.structure as structure
import drawtetrado.svg_painter as svg_painter

from argparse import ArgumentParser

import os
import sys


def Draw(struct, output_file):
    root, ext = os.path.splitext(output_file)
    for idx in range(len(struct.tetrads)):
        quadruplex = structure.Quadruplex(struct, idx)
        config = svg_painter.Config(1.0)  # 1.0 - Scale
        svg_maker = svg_painter.SvgMaker(config, root + "_" + str(idx) + ext, \
                quadruplex)

        # OPTIMIZE, Takes argument "optimizer" with location to the optimizer
        # binary. Default is "./svg_optimizer"
        quadruplex.Optimize()

        # Prepare + Draw
        svg_maker.DrawAll()

        # Save
        svg_maker.svg.save(pretty=True)

        # Also draw sinle tetrads from quadruplex structure.
        if (len(struct.single_tetrads[idx]) > 1):
            for tetrad_idx in range(len(struct.single_tetrads[idx])):
                quadruplex = structure.Quadruplex(struct, idx, tetrad_idx)
                config = svg_painter.Config(1.0)  # 1.0 - Scale
                svg_maker = svg_painter.SvgMaker(config, root + "_" + str(idx) + \
                        "_" + str(tetrad_idx) + ext, quadruplex)

                # OPTIMIZE, Takes argument "optimizer" with location to the optimizer
                # binary. Default is "./svg_optimizer"
                quadruplex.Optimize()

                # Prepare + Draw
                svg_maker.DrawAll()

                # Save
                svg_maker.svg.save(pretty=True)


def DrawFromString(json, output_file):
    Draw(structure.Structure().fromString(json), output_file)


def DrawFromFile(filename_json, output_file):
    Draw(structure.Structure().fromFile(filename_json), output_file)


def main():
    parser = ArgumentParser('drawtetrado',
                            epilog='The output path is a template. For example, '
                            'if output=/tmp/out.svg, the resulting files will be /tmp/out_0.svg, '
                            '/tmp/out_1.svg and so on (for as many distinct quadruplexes as there '
                            'are in the input file)')
    parser.add_argument('input', help='path to input JSON generated by ElTetrado')
    parser.add_argument('output', help='path to output SVG file template')
    args = parser.parse_args()

    DrawFromFile(args['input'], args['output'])
