#!/usr/bin/env python
"""
interactively bypass devices from MPS bypass recover file.
"""
import os
import sys
import optparse
import sqlite3
import operator
import textwrap
#import mpsbypass_R1_0_1 as mpsbypass
#import subprocessca_R1_0_4 as subprocessca
#import slacepics_R1_0_1 as slacepics

import mpsbypass
import subprocessca
import slacepics

__author__ = 'Stephen Norum <snorum@slac.stanford.edu>'
__version__ = "2.0.1"

_title_width = 60

def dhms(seconds):
    """
    Return days:hours:min:sec string for number of seconds
    """
    seconds = int(seconds)
    s = seconds % 60
    m = (seconds / 60) % 60
    h = (seconds / 3600) % 24
    d = seconds / (3600 * 24)
    
    return '%d:%02d:%02d:%02d' % (d, h, m, s)

def hms(seconds):
    """
    Return hours:min:sec string for number of seconds
    """
    seconds = int(seconds)
    s = seconds % 60
    m = (seconds / 60) % 60
    h = seconds / 3600
    
    return '%d:%02d:%02d' % (h, m, s)

def bypass_devices(bypass_info, bypasses_recovered_pv):
    # Set bypassed recovered PV to 0
    print
    print 'Entering bypass recover mode'
    print bypasses_recovered_pv
    try:
        subprocessca.put(bypasses_recovered_pv, 0)
    except ValueError as e:
        print
        print "Error: Couldn't set bypass recovering PV to 0", e
        return 1

    # Bypass inputs
    for bypass in bypass_info:
        pv_prefix = bypass['pv_prefix']
        bypass_control_pv = pv_prefix + '_BYPC'
        bypass_value_pv = pv_prefix + '_BYPV'
        bypass_time = str(bypass['current_time_remaining'])
        bypass_value = str(bypass['value'])

        print 'Bypassing: %s to %s for %s' % (pv_prefix, bypass_value, dhms(bypass_time))

        try:
            subprocessca.put(bypass_value_pv, bypass_value)
            subprocessca.put(bypass_control_pv, bypass_time)
        except ValueError as e:
            print
            print "!!! Error: Couldn't bypass PV !!!"
            print e

    # Set bypasses recovered PV to 1
    print 'Leaving bypass recover mode'
    print

    try:
        subprocessca.put(bypasses_recovered_pv, 1)
    except ValueError as e:
        print "Error: Couldn't set bypass recovering PV.", e
        return 1
        
    return 0

def clear_bypass_recover_fault(bypasses_recovered_pv):
    print 'Clear the bypass recover fault [Y/n]?',
    try:
        answer = sys.stdin.readline()
    except KeyboardInterrupt:
        pass
    
    if not answer.strip():
        answer = 'y'
        
    if answer[0].lower() != 'y':
        print 'Bypass recovery cancelled.'
        return 0
    
    print 'Bypass recover fault cleared.'
    try:
        subprocessca.put(bypasses_recovered_pv, 1)
    except ValueError as e:
        print "Error: Couldn't set bypass recovering PV.", e
        return 1
    
    return 0

def print_bypass_info(bypass_info):
    if not bypass_info:
        print
        print 'No items to bypass.'
        return

    pv_names = map(operator.itemgetter('pv_prefix'), bypass_info)

    max_pv_len = max(map(len, pv_names))
    time_remaining_len = 16
    value_len = len('Value')

    print 'Device'.center(max_pv_len),
    print 'Value',
    print 'Duration'.center(time_remaining_len)
    print '-' * max_pv_len,
    print '-' * value_len,
    print '-' * time_remaining_len

    for bypass in bypass_info:
        print bypass['pv_prefix'].ljust(max_pv_len),
        print str(bypass['value']).center(value_len),
        print (dhms(bypass['original_time_remaining']) + '   ').rjust(time_remaining_len)

def brf_menu(brf_list, max_brfs=3):
    print textwrap.dedent(
        '''
        The Link Processor creates a new bypass recover file on startup. The file is
        updated whenever a bypass is set or expires and when a bypass value changes.
        The most recent bypass recover files are listed below. The MPS LinkProcesor
        Faults the MPS after it has been rebooted until the Byapasses are been recovered.
        Select a recovery file to restore bypassed values and times which will also clear
        the Bypass Recovery MPS Fault. If one does not want to selected any file listed
        but would like to clear the MPS Recovery Fault, Select "0" to only clear the
        MPS Recovery Fault. 
        '''
    )
    
    if max_brfs == 0:
        max_brfs = len(brf_list) # show all if max_brfs = 0

    if len(brf_list) < max_brfs:
        max_brfs = len(brf_list)

    brf_list = brf_list[-1 * max_brfs:]
    
    item_format = '%5d) %s'
    print item_format % (0, 'Clear bypass recover fault')
    for i, brf in enumerate(brf_list):
        print item_format % (i + 1, brf.boot_datetime)
    
    default_choice = i + 1
    
    print
    print 'Choose bypass recover file [{0}]:'.format(default_choice),
    choice = sys.stdin.readline()
    
    if not choice.strip():
        choice = default_choice
    
    try:
        choice = int(choice)
    except ValueError:
        print "Invalid choice.  Using default (%d)." % (default_choice)
        choice = default_choice
    
    if choice == 0:
        return None
    
    choice -= 1
    if choice < 0 or choice >= len(brf_list):
        print "Invalid choice.  Using default (%d)." % (default_choice)
        choice = default_choice - 1
        
    return brf_list[choice]

def process_options(argv):
    '''
    Return parsed command-line options found in the list of
    arguments, `argv`, or ``sys.argv[1:]`` if `argv` is `None`.
    '''

    if argv is None:
        argv = sys.argv[1:]

    usage = 'Usage: %prog CONFIG_DIR FACILITY [options]'    
    version = '%prog 0.1'
    parser = optparse.OptionParser(usage=usage, version=version)
    parser.add_option(
        '-p', '--path', action='store', type='string',
        dest='path', metavar='DIR',
        help='Path to bypass recover file directory (Default: .)'
    )
    parser.add_option(
        '-n', '--nbrf', action='store', type='int',
        dest='max_brf', metavar='MAX',
        help='Maximum number of recover files to list (Defult: 3)'
    )

    parser.set_defaults(verbose=False,
                        path=os.getcwd(),
                        max_brf=3)

    (options, args) = parser.parse_args(argv)

    if len(args) < 2:
        print args
        parser.error("incorrect number of arguments")

    options.config_path = os.path.normcase(args[0])
    options.pv = os.path.normcase(args[1])

    return options 

def main(argv):

    options = process_options(argv)

    options.pv

    brf_list = mpsbypass.bypass_recover_file_list(options.path)
    
    if not brf_list:
        print 'No bypass recover files found.'
        return 1
    
    brf_list.sort()
    try:
        chosen_brf = brf_menu(brf_list, options.max_brf)
    except KeyboardInterrupt:
        print
        print 'Bypass recovery cancelled.'
        return 0

    if not chosen_brf:
        return clear_bypass_recover_fault(options.pv)
    
    try:
        bypass_info = mpsbypass.full_bypass_info(chosen_brf, options.config_path)
    except IOError as e:
        print e
        return 1
    
    print
    print '=' * _title_width
    print 'Bypass Information'.center(_title_width)
    print '=' * _title_width
    print 'Bypass recover file: %s' % chosen_brf.path
    print '  MPS configuration: %s' % os.path.join(options.config_path, chosen_brf.config_db_version)

    if not bypass_info:
        print
        print 'No items to bypass.'
        return clear_bypass_recover_fault(options.pv)

    print
    print 'Times formatted as days:hours:min:sec'
    print
        
    print_bypass_info(bypass_info)
    
    print
    print 'Bypass these devices [Y/n]?',
    try:
        answer = sys.stdin.readline()
    except KeyboardInterrupt:
        print
        answer = 'n'
    
    if not answer.strip():
        answer = 'y'
        
    if answer[0].lower() != 'y':
        print 'Bypass recovery cancelled.'
        return 0
        
    status = bypass_devices(bypass_info, options.pv)

    return status

if __name__ == '__main__':
    status = main(sys.argv[1:])
    sys.exit(status)
