import argparse_tools as at
import os
import time

from relay import log, configure_logging
from relay import util

configure_logging(True)


def main(ns):
    log.info("Starting relay!", extra=dict(**ns.__dict__))
    metric = ns.metric()
    while True:
        if next(metric) > 0:
            ns.launcher(1)
        time.sleep(ns.delay)


build_arg_parser = at.build_arg_parser([
    at.add_argument(
        '-m', '--metric', required=True,
        type=lambda x: util.load_obj_from_path(x, prefix='relay.metrics'),
        help=(
            'Please supply the name of a supported relay metric plugin or'
            ' a python import path that will load your own custom plugin. '
            ' This should point to generator (function or class) that,'
            ' when called, returns a metric value.'
            '  Valid examples:\n'
            '  "Always1"  (this loads relay.metrics.Always1),\n'
            '  "relay.metrics.Always1",\n'
            '  "mycode.custom_metric.plugin"\n'
        )),
    at.add_argument(
        '-l', '--launcher', required=True,
        type=lambda x: util.load_obj_from_path(x, prefix='relay.launchers'),
        help=(
            'Please supply the name of a supported relay launcher plugin or'
            ' a python import path that will load your own custom plugin. '
            ' This should point to a function or class that ....'  # TODO
            '  Valid examples:\n'
            '  "bash_echo",\n'
            '  "relay.launchers.bash_echo",\n'
            '  "mycode.custom_launcher.plugin"\n'
        )),
    at.add_argument(
        '--delay', type=int, default=os.environ.get('RELAY_DELAY', 1),
        help='num seconds to wait between metric polling'),
])

@@ -233,16 +233,88 @@
 etric()%0A
+    # Implement the PID algorithm%0A    # TODO: finish%0A    SP = ns.target%0A
     whil
@@ -333,10 +333,12 @@
     
-if
+PV =
  nex
@@ -346,16 +346,37 @@
 (metric)
+%0A        if (PV - SP)
  %3E 0:%0A  
@@ -897,16 +897,100 @@
 c value.
+  In a PID controller, this'%0A            ' corresponds to the process variable (PV).
 '%0A      
@@ -1544,35 +1544,120 @@
 ion 
-or class that ....'  # TODO
+that executes your task.  In a'%0A            ' PID controller, this corresponds to the manipulated variable (MV)'
 %0A   
@@ -1840,32 +1840,386 @@
 t.add_argument(%0A
+        '-t', '--target', default=0, type=int, help=(%0A            %22A target value that the metric we're watching should stabilize at.%22%0A            ' For instance, if relay is monitoring a queue size, the target'%0A            ' value is 0.  In a PID controller, this value corresponds'%0A            ' to the setpoint (SP).'%0A        )),%0A    at.add_argument(%0A
         '--delay

add --target. update -h message.