from pycomm.ab_comm.clx import Driver as plcDriver
import sys


def readMicroTag(addr, tag):
    addr = str(addr)
    tag = str(tag)
    c = plcDriver()
    if c.open(addr, True):
        try:
            v = c.read_tag(tag)
            # print(v)
            return v
        except Exception:
            err = c.get_status()
            c.close()
            print "{} on reading {} from {}".format(err, tag, addr)
            pass
        c.close()


def getTagType(addr, tag):
    addr = str(addr)
    tag = str(tag)
    c = plcDriver()
    if c.open(addr, True):
        try:
            return c.read_tag(tag)[1]
        except Exception:
            err = c.get_status()
            c.close()
            print err
            pass
        c.close()


def write(addr, tag, val, t):
    addr = str(addr)
    tag = str(tag)
    c = plcDriver()
    if c.open(addr, True):
        try:
            wt = c.write_tag(tag, val, t)
            return wt
        except Exception:
            err = c.get_status()
            c.close()
            print("Write Error: {} setting {} at {} to {} type {}".format(err, tag, addr, val, t))
            return False
        c.close()


def closeEnough(a, b):
    return abs(a - b) <= 0.001


def writeMicroTag(addr, tag, val, handshake=None, handshake_val=None):
    addr = str(addr)
    tag = str(tag)
    print("handshake: {}, handshake_val: {}".format(handshake, handshake_val))
    chk_tag = tag
    if not(handshake is None) and not(handshake == "None"):
        chk_tag = str(handshake)
        print("Handshake tag passed, using {}".format(chk_tag))
    chk_val = val
    if not (handshake_val is None) and not(handshake_val == "None"):
        chk_val = handshake_val
        print("Handshake value passed, using {}".format(chk_val))
    attempts_allowed = 5
    attempts = 1

    while attempts <= attempts_allowed:
        try:
            attempts = attempts + 1
            cv = readMicroTag(addr, tag)
            print("Val Before Write: {}".format(cv))
            if cv:
                if cv[1] == "REAL":
                    val = float(val)
                    chk_val = float(chk_val)
                else:
                    val = int(val)
                    chk_val = int(chk_val)
                wt = write(addr, tag, val, cv[1])
                if wt:
                    print("write: {}".format(wt))
                    chk = readMicroTag(addr, chk_tag)
                    if chk:
                        print("chk: {}, chk_val: {}".format(chk, chk_val))
                        if closeEnough(chk[0], chk_val):
                            return True
        except Exception as e:
            print e
    return False


def readMicroTagList(addr, tList):
    addr = str(addr)
    c = plcDriver()
    if c.open(addr, True):
        vals = []
        try:
            for t in tList:
                v = c.read_tag(t)
                vals.append({"tag": t, "val": v[0], "type": v[1]})
                # print(v)
                # print("{0} - {1}".format(t, v))
        except Exception:
            err = c.get_status()
            c.close()
            print err
            pass
        c.close()
        return vals
if __name__ == '__main__':
    if len(sys.argv) > 2:
        print(readMicroTag(sys.argv[1], sys.argv[2]))
    else:
        print ("Did not pass a target and tag name.")
