#!python
# -- BEGIN LICENSE BLOCK ----------------------------------------------

# catmux
# Copyright (C) 2018  Felix Mauch
# MIT License
#
# 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.
# -- END LICENSE BLOCK ------------------------------------------------

from __future__ import print_function
import os
import subprocess
import site
import sys

import rospkg

import argparse

from catmux.session import Session as CatmuxSession
from catmux.prefix import get_prefix


def safe_call(cmd_list):
    """Makes a subprocess check_call and outputs a clear error message on failure and then exits"""
    try:
        subprocess.check_output(cmd_list)
        return True
    except subprocess.CalledProcessError as err_thrown:
        print('Error while calling "%s"', err_thrown.cmd)
        return False


def parse_arguments(debug=False):
    """Parse command line arguments"""
    parser = argparse.ArgumentParser(description='Create a new catmux session')
    parser.add_argument('session_config',
                        help="Session configuration. Should be a yaml-file.")
    parser.add_argument('-n', '--session_name', default='catmux',
                        help="Name used for the tmux session")
    parser.add_argument('-t', '--tmux_config',
                        help="This config will be used for the tmux session")
    parser.add_argument('-d', '--detach', action='store_true',
                        help="Start session in detached mode")
    parser.add_argument('--overwrite',
                        help="Overwrite a parameter from the session config. Parameters can be "
                             "specified using a comma-separated list such as '--overwrite "
                             "param_a=1,param_b=2'.")

    args = parser.parse_args()
    if debug:
        print(args)
    return args


def main():
    """Creates a new tmux session if it does not yet exist"""
    args = parse_arguments()

    session_config = CatmuxSession(args.session_name, args.overwrite)
    session_config.init_from_filepath(args.session_config)

    try:
        subprocess.check_call(['tmux', 'has-session', '-t', args.session_name])
        print('Session with name "{}" already exists. Not overwriting session.'.format(
            args.session_name))
        sys.exit(0)
    except subprocess.CalledProcessError:
        # When has-session returns non-zero exit code, the session already exists or there is
        # probably something severely wrong. TODO: This could be done better probably
        pass

    command = ['tmux']
    if args.tmux_config:
        tmux_config = args.tmux_config
    elif os.path.exists(os.path.expanduser("~/.tmux.conf")):
        tmux_config = os.path.expanduser("~/.tmux.conf")
    elif os.path.exists("/etc/tmux.conf"):
        tmux_config = "/etc/tmux.conf"
    else:
        prefix = get_prefix()
        tmux_config = os.path.join(prefix,  'share', 'catmux', 'tmux_default.conf')

    print('Using tmux config file: {}'.format(tmux_config))
    command += ['-f', tmux_config]

    command += ['new-session', '-s', args.session_name]
    command.append('-d')
    print(' '.join(command))
    if not safe_call(command):
        sys.exit(1)

    print('Created session "{}"'.format(args.session_name))

    session_config.run()
    if not args.detach:
        safe_call(['tmux', 'attach', '-t', args.session_name])


if __name__ == "__main__":
    main()
