#!/opt/mambaforge/envs/bioconda/conda-bld/pygtftk_1757391569306/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placeh/bin/python
# -*- coding: utf-8 -*-


# Avoid AttributeError: module '__main__' has no attribute '__spec__'.
# A weird bug which seems to be associated to the calling prgm (e.g. spider)
__spec__ = ""

import hashlib
import os
import shutil
import subprocess
import sys
import warnings
from distutils.spawn import find_executable
from subprocess import DEVNULL

import matplotlib as mpl

try:
    mpl.use('Agg')
except:
    pass

import pygtftk
import pygtftk.settings
from pygtftk.cmd_manager import CmdManager
from pygtftk.utils import TMP_FILE_LIST
from pygtftk.utils import flatten_list
from pygtftk.utils import message
from pygtftk.utils import silentremove
from pygtftk.version import __version__

# Avoid warning message emitted by numpy
# https://tinyurl.com/ybev6zrw
warnings.filterwarnings("ignore", message="numpy.dtype size changed")


def main():
    """
    Main function of gtftk command_line. It parses the plugins and call user-defined command.
    """
    # -------------------------------------------------------------------------
    # Declare pygtftk in non-interactive mode
    # -------------------------------------------------------------------------

    pygtftk.__NON_INTERACTIVE__ = True

    # -------------------------------------------------------------------------
    # Search Bedtools
    # -------------------------------------------------------------------------

    if not find_executable("bedtools"):
        message("gtftk needs bedtools (command line version). Please install it.",
                type="ERROR")

    # -------------------------------------------------------------------------
    # Set the hash attribute value of CmdManager. Used to
    # define the path to .gtftk
    # -------------------------------------------------------------------------
    try:
        gtftk_path = subprocess.Popen(['which', 'gtftk'],
                                      stdout=subprocess.PIPE,
                                      stderr=DEVNULL).stdout.read().rstrip()
    except:
        gtftk_path = ''

    CmdManager.hash = hashlib.md5(gtftk_path + __version__.encode()).hexdigest()

    # -------------------------------------------------------------------------
    # Call the command manager
    # and search plugins
    # -------------------------------------------------------------------------

    cmd_manager = CmdManager()
    cmd_manager.load_plugins()

    # -------------------------------------------------------------------------
    # Get the list of arguments values passed through the command
    # -------------------------------------------------------------------------

    args = cmd_manager.parse_cmd_args()
    arg_to_value = dict(args.__dict__)

    pygtftk.__COMMAND__ = arg_to_value['command']
    pygtftk.__ARGS__ = arg_to_value

    del arg_to_value['command']

    # -------------------------------------------------------------------------
    # Call the requested command
    # -------------------------------------------------------------------------

    CmdManager.run(args)

    return args


if __name__ == "__main__":

    from pygtftk.bwig.bw_coverage import TMP_FILE_POOL_MANAGER
    from signal import signal, SIGPIPE, SIG_DFL

    signal(SIGPIPE, SIG_DFL)

    try:

        # Run the main function

        args = main()

        # delete created temporary files

        for i in flatten_list(TMP_FILE_LIST + list(TMP_FILE_POOL_MANAGER), outlist=[]):

            # If the user ask to keep temp files
            if args.tmp_dir is not None:
                message("Keeping temp file : " + i)

                base_name_i = os.path.basename(i)
                shutil.move(i, os.path.join(args.tmp_dir, base_name_i))
            else:
                message("Deleting temp file : " + i, type="DEBUG")
                silentremove(i)

    except KeyboardInterrupt:
        message("Canceled on user request.")
        sys.exit(0)

    sys.exit(0)
