from pycomm.ab_comm.clx import Driver as ClxDriver
import traceback
import math

from app.datalogger.models import Device
from app import db


def getMainPLC():
    dev = Device.query.first()
    dev_obj = dev.serialize
    return dev_obj


def readTag(addr, tag):
    c = ClxDriver()
    if c.open(addr):
        try:
            v = c.read_tag(tag)
            return v
        except Exception:
            print("ERROR RETRIEVING TAG: {}".format(tag))
            c.close()
            traceback.print_exc()
        c.close()


def getTotals():
    today_tags = [
        {'name': "Average SPM", 'tag': "TODAY_Average_SPM", 'min': 0, 'max': 20, 'units': 'SPM'},
        {'name': "Downhole Net Stroke", 'tag': "TODAY_Downhole_NetStroke", 'min': 0, 'max': 150, 'units': 'in'},
        {'name': "Electricity Cost", 'tag': "TODAY_Electricity_Cost", 'min': 0, 'max': 100, 'units': '$'},
        {'name': "Fluid Level", 'tag': "TODAY_Fluid_Above_Pump", 'min': 0, 'max': 10000, 'units': 'ft'},
        {'name': "Inflow Rate", 'tag': "TODAY_Inflow_Rate", 'min': 0, 'max': 100, 'units': 'BBL/day'},
        {'name': "Energy Used", 'tag': "TODAY_kWh", 'min': 0, 'max': 100, 'units': 'kWh'},
        {'name': "Energy Regen", 'tag': "TODAY_kWh_Regen", 'min': 0, 'max': 100, 'units': 'kWh'},
        {'name': "Lifting Cost", 'tag': "TODAY_Lifting_Cost", 'min': 0, 'max': 100, 'units': '$'},
        {'name': "Peak Load", 'tag': "TODAY_Max_Load", 'min': 0, 'max': 50000, 'units': 'lbs'},
        {'name': "Min Load", 'tag': "TODAY_Min_Load", 'min': 0, 'max': 50000, 'units': 'lbs'},
        {'name': "Percent Run", 'tag': "TODAY_Percent_Run", 'min': 0, 'max': 100, 'units': '%'},
        {'name': "Polished Rod HP", 'tag': "TODAY_Polished_Rod_HP", 'min': 0, 'max': 25, 'units': 'HP'},
        {'name': "Calculated Production", 'tag': "TODAY_Production_Calculated", 'min': 0, 'max': 500, 'units': 'BBL'},
        {'name': "Projected Production", 'tag': "TODAY_Production_Projected", 'min': 0, 'max': 500, 'units': 'BBL'},
        {'name': "Pump HP", 'tag': "TODAY_Pump_HP", 'min': 0, 'max': 25, 'units': 'HP'},
        {'name': "Pump Intake Presure", 'tag': "TODAY_Pump_Intake_Pressure", 'min': 0, 'max': 5000, 'units': 'PSI'},
        {'name': "Surface Stroke Length", 'tag': "TODAY_Surface_StrokeLength", 'min': 0, 'max': 150, 'units': 'in'},
        {'name': "Tubing Movement", 'tag': "TODAY_Tubing_Movement", 'min': 0, 'max': 150, 'units': 'in'}
    ]

    main_plc = getMainPLC()
    outList = []
    for tag in today_tags:
        try:
            val = readTag(main_plc['address'], tag['tag'])[0]
            if not math.isnan(val):
                outList.append({'name': tag['name'], 'value': val, 'max': tag['max'], 'min': tag['min'], 'units': tag['units']})
        except Exception as e:
            print("Error while reading total: {}".format(e))

    return outList


if __name__ == '__main__':
    getTotals()
