#! /usr/bin/env python

__author__ = "chevtsov"
__date__ = "$Jul 15, 2010 3:35:05 PM$"

import sys

from subprocess import call
from fbckcontrol import common
import fbckconfig
import optparse
import time
import subprocess

feedback_state = "OFF"

def process_options(argv):
    usage = '%prog feedback_id'
    version = '%prog 1.0 [07-19-2010]'

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

    if len(argv) != 1:
        argv = ["-h"]

    parser = optparse.OptionParser(usage=usage, version=version)
    (options, args) = parser.parse_args(argv)
    options.feedback_id = args[0]
    return options

#
# This is called if the STATE PV is found to be ON. The feedback
# is then turned OFF so the offsets can be zeroed.
#
def turnFeedbackOff(feedback_id):
    pv = fbckconfig.feedback_pv(feedback_id, 'STATE')
    if common.caput(pv, 0):
        print '%s set to 0' % pv
    else:
        print 'Could not reset %s' % pv
        return False

    act_pv = fbckconfig.feedback_pv(feedback_id, 'ACT_STATE')
    state = common.caget(pv)

    for i in range(0, 2):
        if state != 0:
            print 'Feedback not OFF yet, waiting 1 second'
            time.sleep(1)
        else:
            print 'Feedback is currently OFF'
            return True

    return False


def turnFeedbackOn(feedback_id):
    pv = fbckconfig.feedback_pv(feedback_id, 'STATE')
    if common.caput(pv, 1):
        print '%s set to 1' % pv
    else:
        print 'Could not set %s' % pv
        return False

    act_pv = fbckconfig.feedback_pv(feedback_id, 'ACT_STATE')
    state = common.caget(pv)

    for i in range(0, 5):
        if state != 1:
            print 'Feedback not ON yet, waiting 1 second'
            time.sleep(1)
        else:
            print 'Feedback is currently ON'
            return True

    return False

def main(argv):
    options = process_options(argv)
    feedback_id = options.feedback_id

    pv = fbckconfig.feedback_pv(feedback_id, 'ACTREFTS')
    manTS = common.caget(pv)

    pv = fbckconfig.feedback_pv(feedback_id, 'AUTOACTREFTS')
    autoTS = common.caget(pv)



    current_pvs_vals = common.act_pvs_vals(feedback_id)

    if current_pvs_vals == None:
        print "Failed to get current actuator values for %s, try again" % feedback_id
        return

    if current_pvs_vals == None or len(current_pvs_vals) == 0:
        message = "No actuators configured for %s." % feedback_id
        call(["zenity", "--error", "--text", message])
        return

    current_pvs_offsets = common.act_pvs_offsets(feedback_id)
    if current_pvs_offsets == False:
        return
    subcmd = "'\t\tMost Recent\nManual save time: "+manTS+"\nAuto save time:     "+autoTS+"\n\nWhich would you like to restore?\nDefault is Manual'"
    cmd = 'zenity --question --title="Choose Restore Source" --ok-label="Manual" --cancel-label="Auto" --text=' + subcmd
    if (feedback_id != 'FB04:LG01'):
      p = subprocess.Popen(cmd,shell=True)
      streamdata = p.communicate()[0]
      rc=p.returncode
      if (rc != 0):
        actref = 'AUTOACTREF'
        actoffsets = 'AUTOACTOFFSETS'
      else:
        actref = 'ACTREF'
        actoffsets = 'ACTOFFSETS'
    else:
      actref = 'ACTREF'
      actoffsets = 'ACTOFFSETS'

    pv = fbckconfig.feedback_pv(feedback_id, actref)

    original_vals = common.caget(pv)
    if original_vals == None or len(original_vals) == 0:
        message = "Failed to get original actuator references (" + pv + ")"
        call(["zenity", "--error", "--text", message])
        return

    original_offsets = []
    if len(current_pvs_vals) > 0:
        pv = fbckconfig.feedback_pv(feedback_id, actoffsets)
# TEST        pv = "FBCK:FB05:TR04:ACTOFFSETSe"
        original_offsets = common.caget(pv)
        print str(len(original_offsets))
        if original_offsets == None or len(original_offsets) == 0:
            message = "Failed to get original actuator offset references (" + pv + ")"
            call(["zenity", "--error", "--text", message])
            return

    message = "Would you like to restore these actuators?\n\n"
    for i in range(common.nr_acts(feedback_id)):
        pv = fbckconfig.feedback_pv(feedback_id, 'A%dUSED' % (i + 1))
        is_used = common.caget(pv)
        if is_used == None:
            message = "Failed to check whether actuator is in use or not. Could not connect to " + feedback_id + ":A" + str(i+1) + "USED PV."
            call(["zenity", "--error", "--text", message])
            return None

        if is_used == 0:
            continue
        device = current_pvs_vals[2 * i]
        curv = current_pvs_vals[2 * i + 1]
        origv = original_vals[i]
        print '%s  current value: %s   original value: %s' % (device, str(curv), str(origv))

        message += device + "\nFrom " + str(curv) + " to " + str(origv) + "\n\n"

        if len(current_pvs_offsets) <= 0:
            continue
        message += "Offsets:\n"

        offset_pvs = common.act_offset_pvs(device)
        for j in range(len(offset_pvs)):
            offset_index = 4 * i + j
            #pv_o_pv_o
            curo = current_pvs_offsets[2 * offset_index + 1]
            #o_o_o
            origo = original_offsets[offset_index]
            print '%s  current offset: %s   original offset: %s' % (offset_pvs[j], str(curo), str(origo))
            message += str(j) + ": from " + str(curo) + " to " + str(origo) + "\n"
        message += "\n"

#    # Pop-up question on whether to update actuators or not
#    try:
#        exit_code = subprocess.check_call(["zenity", "--question", "--title", "Restore Actuators?", "--text", message])
#    except subprocess.CalledProcessError:
#        print 'Actuators were not restored.'
#        return

    # First check the feedback state
    pv = fbckconfig.feedback_pv(feedback_id, 'STATE')
    state = common.caget(pv)
    if state != 0:
        global feedback_state
        feedback_state = "ON"
        if turnFeedbackOff(feedback_id) == False:
            message = "Feedback " + feedback_id + " (" + name + ") could not be turned OFF.\n"
            message = message + "Please try turning it OFF in order to restore actuators."
            call(["zenity", "--error", "--text", message, "--title", name + " feedback is on"])
            return False

    print 'Restoring actuators...'
    act_pvs = []
    for i in range(common.nr_acts(feedback_id)):
        pv = fbckconfig.feedback_pv(feedback_id, 'A%dUSED' % (i + 1))
        is_used = common.caget(pv)
        if is_used == 0:
            continue
        pv = fbckconfig.feedback_pv(feedback_id, 'A%dDEVNAME' % (i + 1))
        pv = common.caget(pv)
        if common.caput(pv, original_vals[i]) == False:
            message = "Failed to restore actuator " + pv + " with the value " + str(original_vals[i]) + ". Please try restoring again."
            call(["zenity", "--error", "--text", message])
            return
        act_pvs.append(pv)

        # There are no offsets to be restored
        if current_pvs_offsets == []:
            continue

        if len(original_offsets) <= 0:
            continue

        j = 0
        for pv in common.act_offset_pvs(pv):
            if (common.caput(pv, original_offsets[4 * i + j]) == False):
                message = "Failed to restore actuator offset " + pv + " with the value " + str(original_offsets[i]) + ". Please try restoring again."
                call(["zenity", "--error", "--text", message])
                return
            j = j + 1


    # If feedback was ON, turning it ON again
    if feedback_state == "ON":
        turnFeedbackOn(feedback_id)

    print 'Actuators restored.'

    # Pop-up describing what happened
    i = 0
    j = 0
    message = "Actuator references for " + feedback_id + " restored:\n\n"
    for act_pv in act_pvs:
        message += str(act_pv)
        message += " "
        message += str(original_vals[i]) + '\n'

        if current_pvs_offsets != []:
            message += "\nOffsets:\n"
            for k in range(4):
                message += str(k) + ": "
                message += str(original_offsets[j])
                message += "\n"
                j += 1
            message += "\n"

        i += 1


#    call(["zenity", "--info", "--text", message])    


if __name__ == "__main__":
    main(sys.argv[1:])
    time.sleep(1.5)
