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, config = svg_painter.Config(1.0)):
    root, ext = os.path.splitext(output_file)
    for idx in range(len(struct.tetrads)):
        quadruplex = structure.Quadruplex(struct, idx)
        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 single 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)
                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, config = svg_painter.Config(1.0)):
    Draw(structure.Structure().fromString(json), output_file, config)


def DrawFromFile(filename_json, output_file, config = svg_painter.Config(1.0)):
    Draw(structure.Structure().fromFile(filename_json), output_file, config)

def main():
    parser = ArgumentParser('drawtetrado',
        epilog='The output path is a template. Program will generate drawings for each ' \
        'individual quadruplex in each helice as well as each full helice.' \
        'If we have file with 2 helices with 2 quadruplexes each, if output_template=/tmp/out.svg, ' \
        'the resulting files will be /tmp/out_0.svg, with full helice 0, /tmp/out_0_0.svg ' \
        'and /tmp/out_0_1.svg for each quadruplex in helice 0. Similar files will be created ' \
        'for helice 1 with /tmp/out_1.svg and /tmp/out_1_0.svg, /tmp/out_1_1.svg.')
    parser.add_argument('input', help='path to input JSON generated by ElTetrado')
    parser.add_argument('output_template', help='path to output SVG file template')

    parser.add_argument('--config',
            help='JSON config file containing all parameter changes and individual nucleotide '
            'coloring overrides',
            default=None)
    args = parser.parse_args()

    config = svg_painter.Config(1.0, args.config)

    if not args.input and args.output_template:
        print(parser.print_help())
        sys.exit(1)

    DrawFromFile(args.input, args.output_template, config)
