#!/usr/bin/env python3
r"""Argument parser to use ufcc from the command-line
======================================================
:Authors: Daniel P. Ramirez & Besian I. Sejdiu
:Year: 2022
:Copyright: MIT License
"""

import argparse
import ufcc._version as vers
from ufcc.server.server import start_server
import configparser
from ufcc import get_config
import os

# Getting the config file
config = configparser.ConfigParser(allow_no_value=True)
config.read(get_config())
parameters_config = config["Parameters"]

# Creating the parser
ufcc_parser = argparse.ArgumentParser(
    prog="ufcc",
    usage="%(prog)s [optional-arguments] structure_file trajectory_file",
    description="Argument parser to use the ufcc library directly from the command-line.",
    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    epilog="Have fun getting lipid-protein contacts! :)\n",
)

ufcc_parser.version = vers.get_versions()["version"]

# dealing with boolean arguments
def str2bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ("yes", "true", "t", "y", "1"):
        return True
    elif v.lower() in ("no", "false", "f", "n", "0"):
        return False
    else:
        raise argparse.ArgumentTypeError("Boolean value expected.")


# positional arguments
# structure_file
ufcc_parser.add_argument(
    "structure", action="store", type=str, help="path to the structure/topology file."
)

# trajectory_file
ufcc_parser.add_argument(
    "trajectory", action="store", type=str, help="path to the trajectory file."
)

# optional arguments
# version
ufcc_parser.add_argument("-v", "--version", action="version")

# Cut-off
ufcc_parser.add_argument(
    "-c",
    "--cutoff",
    metavar="",
    type=int,
    help="distance cutoff to get the contacts (in angstroms).",
    default=int(parameters_config["cutoff"]),
    dest="cutoff",
)

# add lipids
ufcc_parser.add_argument(
    "-al",
    "--add_lipid_types",
    nargs="+",
    metavar="",
    help="additional lipid types to be included in the membrane group, supported lipid types are POPC, DPPC, DOPC, CHOL, CHL1, POPS and POPE.",
    dest="other_lipids",
    default=[],
)

# interactive mode
ufcc_parser.add_argument(
    "-i",
    "--interactive",
    metavar="",
    type=str2bool,
    nargs="?",
    const=True,
    default=False,
    help="interactive selection of the groups for the calculation of the contacts.",
    dest="i_bool",
)


def file_extension(choices, fname):
    ext = os.path.splitext(fname)[1][1:]
    if ext not in choices:
        ufcc_parser.error(
            "Filename for exporting contacts doesn't end with {}.".format(choices)
        )
    return fname


# export contacts data
ufcc_parser.add_argument(
    "-e",
    "--export",
    metavar="",
    type=lambda s: file_extension(("csv"), s),
    nargs="?",
    help="exporting results of the contacts to a file.",
    default=False,
    const="contacts.csv",
    dest="e_file",
)

# Executing the parse_args() method
args = ufcc_parser.parse_args()

# Starting the server
start_server(payload=args, reloader=False, i_bool=args.i_bool, e_file=args.e_file)
import sys

sys.exit()
