from pycomm_micro.ab_comm.clx import Driver as u800Driver
import logging
import sys


def readMicroTag(addr, tag):
    logging.basicConfig(
        filename="u800Driver.log",
        format="%(levelname)-10s %(asctime)s %(message)s",
        level=logging.DEBUG
    )
    c = u800Driver()

    if c.open(addr):
        try:
            v = c.read_tag(tag)
            # print(v)
            return v
        except Exception as e:
            err = c.get_status()
            c.close()
            print err
            pass
        c.close()

def getTagType(addr, tag):
    logging.basicConfig(
        filename="u800Driver.log",
        format="%(levelname)-10s %(asctime)s %(message)s",
        level=logging.DEBUG
    )
    c = u800Driver()

    if c.open(addr):
        try:
            return c.read_tag(tag)[1]
        except Exception as e:
            err = c.get_status()
            c.close()
            print err
            pass
        c.close()

def writeMicroTag(addr, tag, val):
    logging.basicConfig(
        filename="u800Driver.log",
        format="%(levelname)-10s %(asctime)s %(message)s",
        level=logging.DEBUG
    )
    c = u800Driver()

    if c.open(addr):
        try:
            #typ = getTagType(addr, tag)
            cv = c.read_tag(tag)
            wt = c.write_tag(tag, val, cv[1])
            # print(wt)
            return wt
        except Exception as e:
            err = c.get_status()
            c.close()
            print err
            pass
        c.close()


def readMicroTagList(addr, tList):
    logging.basicConfig(
        filename="u800Driver.log",
        format="%(levelname)-10s %(asctime)s %(message)s",
        level=logging.DEBUG
    )
    c = u800Driver()

    if c.open(addr):
        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 as e:
            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.")
