#! /usr/bin/env python

__author__ = "lpiccoli"

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

def process_options(argv):
    usage = '%prog feedback_id act_num\nThis script zeroes the offsets for a single actuator.'
    version = '%prog 1.0 [07-19-2010]'

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

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

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

    return options

# Feedback must be OFF and all actuator PVs must be OFF as well in order
# to zero all offsets.
def checkFeedbackState(feedback_id, act_num, name):
    # First check the feedback state SxxUSED
    state_name_pv = fbckconfig.feedback_pv(feedback_id, 'S%dNAME' % act_num)
    state_name = common.caget(state_name_pv)
    if (state_name is None):
        message = "Failed to read " + state_name_pv
        call(["zenity", "--error", "--text", message, "--title", "Error"])
        return False

    pv = fbckconfig.feedback_pv(feedback_id, 'STATE')
    feedback_state = common.caget(pv)
    if (feedback_state is None):
        message = "Failed to read " + pv
        call(["zenity", "--error", "--text", message, "--title", "Error"])
        return False

    pv = fbckconfig.feedback_pv(feedback_id, 'MODE')
    feedback_mode = common.caget(pv)
    if (feedback_mode is None):
        message = "Failed to read " + pv
        call(["zenity", "--error", "--text", message, "--title", "Error"])
        return False

    # If feedback is turned on && feedback mode is ENABLE (1) then the SxxUSED must be Disabled,
    # If feedback is turned off then SxxUSED is not verified.
    if feedback_state != 0 and feedback_mode != 0:
        pv = fbckconfig.feedback_pv(feedback_id, 'S%dUSED' % act_num)
        state = common.caget(pv)
        if (state is None):
            message = "Failed to read " + state_name_pv
            call(["zenity", "--error", "--text", message, "--title", "Error"])
            return False

        if state != 0:
            message = "State " + state_name + " is Activated.\n"
            message = message + "It must be Disabled in order to zero the offsets."
            call(["zenity", "--error", "--text", message, "--title", state_name + " state is Activated"])
            return False

    # If we got to this point then the feedback is:
    # state=ON and mode=ENABLE and SxxUSED=FALSE or
    # state=OFF and mode=ENABLE/COMPUTE and SxxUSED=TRUE/FALSE or
    # state=ON/OFF and mode=COMPUTE and SxxUSED=TRUE/FALSE or

    # Now make sure the FBCK PVs are all off
    pv = fbckconfig.feedback_pv(feedback_id, 'A%dDEVNAME' % act_num)
    act_pv = common.caget(pv)
    if (act_pv is None):
        message = "Failed to read " + pv
        call(["zenity", "--error", "--text", message, "--title", name + " Error"])
        return False

    fbck_pv = act_pv + ":FBCK"
    
    message = "Cannot zero the offsets for " + act_pv + "\n\n"
    message = message + "The following actuator FBCK PV is ON:\n\n"
    
    fbck_value = common.caget(fbck_pv)
    if (fbck_value is None):
        message = "Failed to read " + fbck_pv
        call(["zenity", "--error", "--text", message, "--title", name + " Error"])
        return False
    
    if (fbck_value != 0):
        message = message + "  " + fbck_pv + "\n"
        message = message + "\nPlease Disable the desired state before trying again."
        call(["zenity", "--error", "--text", message, "--title", state_name + ": cannot zero offsets!"])
        return False

    return True

def checkActNum(feedback_id, act_num, name):
    pv = fbckconfig.feedback_pv(feedback_id, 'ACTNUM')
    num_acts = common.caget(pv)
    if (name is None):
        message = "Failed to read " + pv
        call(["zenity", "--error", "--text", message, "--title", "Error"])
        return False

    if (act_num >= 1 and act_num <= num_acts):
        return True
    else:
        message = "Invalid actuator number " + str(act_num) + ".\n"
        message = message + "Number must be between 1 and " + str(num_acts) + "."
        call(["zenity", "--error", "--text", message, "--title", name + " Error"])
        return False

def toggleFbckPv(feedback_id, act_num): 
    pv = fbckconfig.feedback_pv(feedback_id, 'A%dDEVNAME' % act_num)
    act_pv = common.caget(pv)
    if (act_pv is None):
        message = "Failed to read " + pv
        call(["zenity", "--error", "--text", message, "--title", name + " Error"])
        return False

    fbck_pv = act_pv + ":FBCK"
    
    if (not common.caput(fbck_pv, 1)): 
        message = "Failed to set " + fbck_pv + " to ON.\n\n"
        message = message + "This PV must be turned ON and OFF to make"
        message = message + "the offsets effective!\n\n"
        message = message + "Please turn in ON/OFF using caputs or on"
        message = message + "RF PAU page before activating the state again!"
        call(["zenity", "--error", "--text", message, "--title", name + " Error"])
        return False
    print "Set " + fbck_pv + " ON"

    if (not common.caput(fbck_pv, 0)): 
        message = "Failed to set " + fbck_pv + " to OFF.\n\n"
        message = message + "This PV must be turned ON and OFF to make"
        message = message + "the offsets effective!\n\n"
        message = message + "Please turn in OFF using caput or on"
        message = message + "RF PAU page before activating the state again!"
        call(["zenity", "--error", "--text", message, "--title", name + " Error"])
        return False
    print "Set " + fbck_pv + " OFF"
    
    return True

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

    pv = fbckconfig.feedback_pv(feedback_id, 'NAME')
    name = common.caget(pv)
    if (name is None):
        message = "Failed to read " + pv
        call(["zenity", "--error", "--text", message, "--title", "Error"])
        return False

    # Make sure we've got a valid actuator number
    if not checkActNum(feedback_id, act_num, name):
        exit(-1)
        
    pv = fbckconfig.feedback_pv(feedback_id, 'A%dCAMODE' % act_num)
    is_camode = common.caget(pv)
    if (is_camode is None):
        message = "Failed to read " + pv
        call(["zenity", "--error", "--text", message, "--title", name + " Error"])
        exit(-1)

    # There are no offsets to be cleared if CA is used
    if is_camode == 1:
        print "Feedback " + feedback_id + " uses Channel Access. No offsets to be zeroed!"
    	exit(0)

    # Make sure the feedback is off as well as all the actuator
    # FBCK PVs before clearing the offsets.
    if not checkFeedbackState(feedback_id, act_num, name):
        exit(-1)
    	
    pv = fbckconfig.feedback_pv(feedback_id, 'A%dDEVNAME' % act_num)
    pv = common.caget(pv)
    for pv in common.act_offset_pvs(pv):
        if common.caput(pv, 0):
            print '%s reset to 0' % pv
        else:
            print 'Could not reset %s' % pv
            exit(-1)

# We don't need to do this, Kukhee does make the data copies already
#    toggleFbckPv(feedback_id, act_num)
    

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