#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# This is the main HDTV application.
#-------------------------------------------------------------------------

from __future__ import print_function

import sys
import os
import glob

import argparse

# Reset command line arguments so that ROOT does not stumble about them
hdtv_args = sys.argv[1:]
sys.argv = [sys.argv[0]]

# Get config and data directory
legacypath = os.path.join(os.environ["HOME"], ".hdtv")
configpath = os.getenv("HDTV_USER_PATH",
    legacypath if os.path.isdir(legacypath) else
    os.path.join(os.getenv("XDG_CONFIG_HOME",
        os.path.join(os.environ["HOME"], ".config")), "hdtv"))
datapath = os.getenv("HDTV_USER_PATH",
    legacypath if os.path.isdir(legacypath) else
    os.path.join(os.getenv("XDG_DATA_HOME",
        os.path.join(os.environ["HOME"], ".local", "share")), "hdtv"))

for path in [datapath, configpath]:
    try:
        os.makedirs(path)
    except OSError:
        pass

if not os.access(datapath, os.W_OK) and os.access(configpath, os.W_OK):
    print("Could not access data path " + datapath +
          ", falling back to " + configpath, file=sys.stderr)
    datapath = configpath

if not os.access(configpath, os.R_OK):
    print("Could not access config path " + configpath, file=sys.stderr)

os.environ["HDTV_USER_PATH"] = configpath
sys.path.append(configpath)
sys.path.append(configpath + "/plugins")

# Check if we are inside the hdtv source directory and append
hdtvpath = os.sep.join(sys.path[0].split(os.sep)[:-1])
if os.path.exists(os.path.join(hdtvpath, 'hdtv')):
    sys.path.insert(1, hdtvpath)

# This needs to happen before "import ROOT" is called the first time –
# if not, there will be a header not found error
# for *some* ROOT versions and install methods
import hdtv.rootext
hdtv.rootext.UpdateRootIncludePath()

from hdtv._version import get_versions
__version__ = get_versions()['version']
del get_versions
# Command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--batch", dest="batchfile",
    help="Open and execute HDTV batchfile")
parser.add_argument("-e", "--execute", dest="commands",
    help="Execute HDTV command(s)")
parser.add_argument("-v", "--version", action="version",
    help="Show HDTV Version",
    version="HDTV" + str(__version__))
parser.add_argument("--rebuild-usr", action='store_true', dest='rebuildusr',
    help='Rebuild ROOT-loadable libraries for the current user')
parser.add_argument("--rebuild-sys", action='store_true', dest='rebuildsys',
    help='Rebuild ROOT-loadable libraries for all users')
args = parser.parse_args(hdtv_args)

if args.rebuildusr:
    import hdtv.rootext.dlmgr
    hdtv.rootext.dlmgr.RebuildLibraries(hdtv.rootext.dlmgr.usrdir)
if args.rebuildsys:
    import hdtv.rootext.dlmgr
    hdtv.rootext.dlmgr.RebuildLibraries(hdtv.rootext.dlmgr.sysdir)

if args.rebuildusr or args.rebuildsys:
    sys.exit(0)

# Import core modules
import hdtv.cmdline
import hdtv.session
import hdtv.ui


hdtv.cmdline.ReadReadlineInit(configpath + "/inputrc")
hdtv.cmdline.SetReadlineHistory(datapath + "/hdtv_history")
hdtv.cmdline.SetInteractiveDict(locals())
spectra = hdtv.session.Session()

# Import core plugins
import hdtv.plugins.textInterface
import hdtv.plugins.ls
import hdtv.plugins.run
import hdtv.plugins.specInterface
import hdtv.plugins.fitInterface
import hdtv.plugins.calInterface
import hdtv.plugins.matInterface
import hdtv.plugins.rootInterface
import hdtv.plugins.config
import hdtv.plugins.fitlist
import hdtv.plugins.fittex
import hdtv.plugins.fitmap
import hdtv.plugins.dblookup
import hdtv.plugins.peakfinder
import hdtv.plugins.printing


hdtv.ui.msg("HDTV - Nuclear Spectrum Analysis Tool")


# Execute startup.py for user configuration in python
try:
    import startup
except ImportError:
    hdtv.ui.debug("No startup.py file")

# Execute startup.hdtv and startup.hdtv.d/*.hdtv
# for user configuration in "hdtv" language
startup_d_hdtv = [configpath + os.sep + "startup.hdtv"] + glob.glob(
    configpath + os.sep + "startup.hdtv.d" + os.sep + "*.hdtv")

for startup_hdtv in startup_d_hdtv:
    try:
        if os.path.exists(startup_hdtv):
            hdtv.cmdline.command_line.ExecCmdfile(startup_hdtv)
    except IOError as msg:
        hdtv.ui.error("Error reading %s: %s" % (startup_hdtv, msg))

# Execute batchfile given on command line
try:
    if args.batchfile is not None:
        hdtv.cmdline.command_line.ExecCmdfile(args.batchfile)
except IOError as msg:
    hdtv.ui.msg("Error reading %s: %s" % (args.batchfile, msg))

if args.commands is not None:
    hdtv.cmdline.command_line.DoLine(args.commands)


# Go
hdtv.cmdline.MainLoop()
hdtv.plugins.rootInterface.r.rootfile = None
hdtv.cmdline.command_tree.SetDefaultLevel(1)
