#!/usr/bin/env python

"""
The MIT License (MIT)

Copyright (c) 2013 Jeremy Gillick

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.
"""

import os
import signal
import sys
import daemon
from datetime import datetime
from daemon import runner
import argparse

# Add local paths to support running without installing
if sys.argv[0][0:2] == './':
    sys.path.insert(0, '.')
    sys.path.insert(0, '../')

import LendingClubInvestor

investor = None
pid_lockfilepath = '/tmp/lcinvestor.pid'


def interupt_handler(signum, frame):
        """
        Exit gracefully
        """
        if investor:
            investor.stop()
        else:
            print '\n\nStopping program...\n'
        exit(0)
signal.signal(signal.SIGINT, interupt_handler)


def is_daemon_running():
    """
    Check if the pid locked file status.
    True if the daemon is believed to be running (based on the lockfile)
    False if it is not.
    """
    lockfile = runner.make_pidlockfile(pid_lockfilepath, 1)
    if lockfile.is_locked():
        return True
    return False

if __name__ == '__main__':

    # Process command flags
    parser = argparse.ArgumentParser(usage='Usage: %(prog)s [options] [start/stop]')
    parser.add_argument('--version', action='store_true', default=False, help='Print the lcinvestor version number')
    parser.add_argument('-v', '--verbose', action='store_true', dest='verbose', default=False, help='Verbose output')
    parser.add_argument('start/stop/status', action='store', type=str, nargs='*', help='Start or stop the this as a background task (daemon). Use status to see the current daemon status')
    options = parser.parse_args()

    options.action = options.__dict__['start/stop/status']
    action = options.action[0] if (len(options.action) > 0) else None
    isVerbose = options.verbose
    isDaemon = (action is not None)
    isStarting = ('start' == action)
    isStopping = ('stop' == action)

    # Validate options
    if len(options.action) > 1:
        print 'Too many arguments!'
        exit(1)
    if action is not None and action not in ['start', 'stop', 'status']:
        print '\'{0}\' is not a supported action!'.format(action)
        exit(1)

    # Start program
    try:
        investor = LendingClubInvestor.AutoInvestor(verbose=isVerbose)

        # Print version number
        if options.version:
            print 'lcinvestor {0}'.format(investor.version())
            exit(0)

        # Print daemon status and exit
        if action == 'status':
            if is_daemon_running():
                print 'The lcinvestor daemon is running'

                # Print info on the last investment
                last_investment = investor.get_last_investment()
                if last_investment:
                    timestamp = datetime.fromtimestamp(last_investment['timestamp'])

                    print '\nLast investment:'
                    print '${0} was invested at {1}'.format(last_investment['cash'], timestamp.strftime("%A %B %d, %Y at %I:%M%p"))
                    print investor.get_option_summary(last_investment['investment'])
            else:
                print 'The lcinvestor daemon is not running'
            exit(0)

        # Start daemon
        if isDaemon:

            # Set daemon attributes
            logfile_path = os.path.join(investor.app_dir, 'daemon.log')
            investor.stdin_path = '/dev/null'
            investor.stdout_path = logfile_path
            investor.stderr_path = logfile_path
            investor.pidfile_path = pid_lockfilepath
            investor.pidfile_timeout = 1

            # Check if the pid locked file ststus
            if is_daemon_running():
                if isStarting:
                    print 'It looks like an investor daemon is already running!\nIf this is incorrect, delete \'{0}\' and try again.'.format(investor.pidfile_path)
                    exit(1)
            else:
                if isStopping:
                    print 'It doesn\'t look like there is an investor daemon running.'
                    exit(1)

            if isStarting:
                investor.setup()
                print 'Starting auto investor daemon...'
                print 'pid at {0}'.format(investor.pidfile_path)
                print 'Logging output to {0}'.format(logfile_path)
            else:
                print 'Stopping auto investor daemon...'

            # Start daemon
            try:
                daemon_runner = runner.DaemonRunner(investor)
                daemon_runner.do_action()
            except daemon.runner.DaemonRunnerStartFailureError as e:
                print 'Could not start daemon: {0}'.format(str(e))
            except daemon.runner.DaemonRunnerStopFailureError as e:
                print 'Could not stop daemon: {0}'.format(str(e))

        # Start in the foreground
        else:
            investor.setup()
            investor.run()

    except LendingClubInvestor.AutoInvestorError as e:
        print 'ERROR: {0}'.format(str(e))
        exit(1)
