#! /usr/bin/env python

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

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

def process_options(argv):
    usage = '%prog feedback_id|"all"'
    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)
    parser.add_option("-s", "--show_editor",
                      action="store_true", dest="show_editor", default=False,
                      help="show the data editor before update")

    (options, args) = parser.parse_args(argv)
    options.feedback_id = args[0]
    return options

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

    if options.feedback_id == 'all':
        feedback_ids = fbckconfig.TRANSVERSE_FEEDBACK_IDS
    else:
        feedback_ids = [options.feedback_id]

    for feedback_id in feedback_ids:
        pv = fbckconfig.feedback_pv(feedback_id, 'INSTALLED')
        installed = common.caget(pv)
        if installed == None:
            message = "Failed to find whether feedback is installed or not: " + pv + ". Please try again."
            call(["zenity", "--error", "--text", message, "--title", "Error"])
            return

        if installed != 1:
            continue

        print 'Acquiring actuator data for %s...' % feedback_id

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

        # Pop-up question on whether to save actuators or not
        try:
            message = "Would you like to save current actuator references?"
            exit_code = subprocess.check_call(["zenity", "--question", "--title", "Update Actuators?", "--text", message])
        except subprocess.CalledProcessError:
            print 'Actuators were not saved.'
            return

        print 'Acquiring actuator offsets for %s...' % feedback_id
        act_pvs_offsets = common.act_pvs_offsets(feedback_id)
        if act_pvs_offsets == False:
            return

        #open WF editor
        pv = fbckconfig.feedback_pv(feedback_id, 'NAME')
        fbck_name = common.caget(pv)
        if fbck_name == None:
            message = "Failed to retrieve feedback name: " + pv + ". Please try again."
            call(["zenity", "--error", "--text", message])
            return

        if options.show_editor:
            print 'Actuator data for %s collected.\n' % feedback_id

            act_vals = ' '.join(map(str, act_pvs_vals))
            act_offsets = ' '.join(map(str, act_pvs_offsets))
            wfeditor_args = common.WFEDITOR_MAIN_ARGS
            wfeditor_args.append(fbck_name)
            wfeditor_args.append('='.join(['Actuator Values', act_vals]))
            wfeditor_args.append('='.join(['Actuator Offsets', act_offsets]))
            print 'Launching data editor...'

            process = subprocess.Popen(wfeditor_args, stdout=subprocess.PIPE)
            (stdoutdata, stderrdata) = process.communicate()

            if stdoutdata == None or len(stdoutdata) == 0:
                return

            output = eval(stdoutdata)

            if output != None and len(output) > 1:
                act_vals = output[0]
                act_offsets = output[1]
        else:
            act_vals = act_pvs_vals[1::2]
            act_offsets = act_pvs_offsets[1::2]

        print act_vals
        print act_offsets


        print 'Updating actuator references for %s...' % feedback_id
        if (common.update_act_refs(feedback_id, act_vals) == False):
            print 'Failed to update references, try again!'
            exit(-1)
            
        if (common.update_act_offsets(feedback_id, act_offsets) == False):
            print 'Failed to update offsets, try again!'
            exit(-1)

        print 'Actuator references for %s updated.' % feedback_id

        if options.feedback_id != 'all':
            # Pop-up describing what happened
            i = 0
            message = "Actuator references for " + feedback_id + " updated:\n\n"
            for x in act_pvs_vals:
                i += 1
                message += str(x)
                message += " "
                if i % 2 == 0:
                    message += '\n'

            # Show offsets if feedback uses FCOM
            if act_pvs_offsets != []:
                message += '\n'
                message += "Actuator offsets:\n\n"
                i = 0
                j = 0
                for x in act_pvs_vals:
                    i += 1
                    if i % 2 != 0:
                        message += str(x)
                        message += "\n"
                        for k in range(4):
                            message += str(k) + ": " 
                            message += str(act_offsets[j])                        
                            message += "\n"
                            j += 1
                        message += "\n"


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


    if options.feedback_id == 'all':
        call(["zenity", "--info", "--text", "All transverse feedback actuators updated!",
              "--title", "Success"])
        
if __name__ == "__main__":
    main(sys.argv[1:])
    time.sleep(1.5)
