# -*- coding: utf-8 -*-
"""
This is a skeleton file that can serve as a starting point for a Python
console script. To run this script uncomment the following lines in the
[options.entry_points] section in setup.cfg:

    console_scripts =
         fibonacci = interneuron_polarity.skeleton:run

Then run `python setup.py install` which will install the command `fibonacci`
inside your current environment.
Besides console scripts, the header (i.e. until _logger...) of this file can
also be used as template for Python modules.

Note: This skeleton file can be safely removed if not needed!
"""

import argparse
import logging
import os
import sys

from interneuron_polarity import __version__
from interneuron_polarity.actions.create_connectivity import create_connectivity
from interneuron_polarity.actions.create_spatial_arrangement import create_spatial_arrangement
from interneuron_polarity.actions.plot_network_activity import plot_network_activity
from interneuron_polarity.actions.plot_spatial_configuration import plot_spatial_configuration
from interneuron_polarity.actions.simulate_network_activity import simulate_network_activity

__author__ = "Paul Pfeiffer"
__copyright__ = "Paul Pfeiffer"
__license__ = "mit"

_logger = logging.getLogger(__name__)

ACTION_CHOICES = ['all', 'space', 'conn', 'act', 'ana_act', 'plot_space', 'plot_act']


def parse_args(args):
    """Parse command line parameters

    Args:
      args ([str]): command line parameters as list of strings

    Returns:
      :obj:`argparse.Namespace`: command line parameters namespace
    """
    parser = argparse.ArgumentParser(
        description="Analyze network connectivity and activity in a network with different interneuron axon "
                    "morphologies")
    parser.add_argument(
        "--version",
        action="version",
        version="interneuron_polarity {ver}".format(ver=__version__))
    parser.add_argument(
        dest="action",
        help="analysis step to perform",
        choices=ACTION_CHOICES,
        type=str

    )
    parser.add_argument(
        "-d",
        "--directory",
        dest="dir",
        help="directory with simulation specifications",
        type=str
    )
    parser.add_argument(
        "-v",
        "--verbose",
        dest="loglevel",
        help="set loglevel to INFO",
        action="store_const",
        const=logging.INFO)
    parser.add_argument(
        "-vv",
        "--very-verbose",
        dest="loglevel",
        help="set loglevel to DEBUG",
        action="store_const",
        const=logging.DEBUG)
    return parser.parse_args(args)


def setup_logging(loglevel):
    """Setup basic logging

    Args:
      loglevel (int): minimum loglevel for emitting messages
    """
    logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
    logging.basicConfig(level=loglevel, stream=sys.stdout,
                        format=logformat, datefmt="%Y-%m-%d %H:%M:%S")


def analyze_network_activity(simulation_dir):
    pass

def main(args):
    """Main entry point allowing external calls

    Args:
      args ([str]): command line parameter list
    """
    args = parse_args(args)
    setup_logging(args.loglevel)

    path_to_simulation_dir = os.path.abspath(args.dir)

    _logger.info("Analysis {:s} in {:s}".format(args.action, path_to_simulation_dir))

    action_dict = {"space": create_spatial_arrangement,
                   "conn": create_connectivity,
                   "act": simulate_network_activity,
                   "ana_act": analyze_network_activity,
                   "plot_space": plot_spatial_configuration,
                   "plot_act": plot_network_activity
                   }
    print(args.action)
    if args.action == "all":
        for action in ACTION_CHOICES[1:]:
            print(action)
            action_dict[action](path_to_simulation_dir)
            print()
    else:
        action_dict[args.action](path_to_simulation_dir)



def run():
    """Entry point for console_scripts
    """
    main(sys.argv[1:])


if __name__ == "__main__":
    run()
