#!/usr/bin/python
#
# Copyright (c) 2013 Mikkel Schubert <MSchubert@snm.ku.dk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import optparse

import paleomix
import paleomix.ui

from paleomix.config import \
     ConfigError, \
     PerHostValue, \
     PerHostConfig, \
     migrate_config


def _run_config_parser(argv, pipeline_variant):
    per_host_cfg = PerHostConfig("bam_pipeline")
    pipeline_variant = "%s_pipeline" % (pipeline_variant,)

    usage_str = "paleomix %s <command> [options] [makefiles]" % (pipeline_variant,)
    version_str = "paleomix %s %s" % (pipeline_variant, paleomix.__version__)
    parser = optparse.OptionParser(usage=usage_str, version=version_str)

    paleomix.ui.add_optiongroup(parser,
                                ui_default=PerHostValue("running"),
                                color_default=PerHostValue("on"))
    paleomix.logger.add_optiongroup(parser, default = PerHostValue("warning"))

    group = optparse.OptionGroup(parser, "Scheduling")
    group.add_option("--dry-run", action="store_true", default=False,
                     help="If passed, only a dry-run in performed, the "
                          "dependency tree is printed, and no tasks are "
                          "executed.")
    group.add_option("--max-threads", type=int, default=per_host_cfg.max_threads,
                     help="Maximum number of threads to use in total [%default]")
    group.add_option("--adapterremoval-max-threads", type=int, default=PerHostValue(1),
                     help="Maximum number of threads to use per AdapterRemoval instance [%default]")
    group.add_option("--bowtie2-max-threads", type=int, default=PerHostValue(1),
                     help="Maximum number of threads to use per Bowtie2 instance [%default]")
    group.add_option("--bwa-max-threads", type=int, default=PerHostValue(1),
                     help="Maximum number of threads to use per BWA instance [%default]")
    group.add_option("--gatk-max-threads", type=int, default=PerHostValue(1),
                     help="Maximum number of threads to use per GATK instance [%default]")
    parser.add_option_group(group)

    group = optparse.OptionGroup(parser, "Required paths")
    group.add_option("--jar-root", default = PerHostValue("~/install/jar_root", is_path = True),
                     help = "Folder containing Picard JARs (http://picard.sf.net), " \
                            "and GATK (www.broadinstitute.org/gatk). " \
                            "The latter is only required if realigning is enabled. " \
                            "[%default]")
    group.add_option("--temp-root", default = per_host_cfg.temp_root,
                     help = "Location for temporary files and folders [%default/]")
    group.add_option("--destination", default = None,
                     help = "The destination folder for result files. By default, files will be "
                            "placed in the same folder as the makefile which generated it.")
    parser.add_option_group(group)

    group = optparse.OptionGroup(parser, "Files and executables")
    group.add_option("--list-output-files", action = "store_true", default = False,
                     help = "List all files generated by pipeline for the makefile(s).")
    group.add_option("--list-executables", action="store_true", default=False,
                     help="List all executables required by the pipeline, "
                          "with version requirements (if any).")
    parser.add_option_group(group)

    group = optparse.OptionGroup(parser, "Misc")
    group.add_option("--jre-option", dest = "jre_options", action = "append", default = PerHostValue([]),
                     help = "May be specified one or more times with options to be passed "
                            "tot the JRE (Jave Runtime Environment); e.g. to change the "
                            "maximum amount of memory (default is -Xmx4g)")
    group.add_option("--to-dot-file", dest="dot_file",
                     help="Write dependency tree to the specified dot-file.")
    parser.add_option_group(group)

    return per_host_cfg.parse_args(parser, argv)


def parse_config(argv, pipeline_variant):
    migrate_config()

    config, args = _run_config_parser(argv, pipeline_variant)
    paleomix.ui.set_ui_colors(config.ui_colors)

    return config, args
