import vedirect
import json
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/orange/battery_info', methods=['GET'])
def get_battery_data():
    device = vedirect.VEDirect("COM3")
    volts = float(str(device._get_data( )[0].decode('ascii')).strip().split("\t")[1])/1000.0
    power_usage = int(str(device._get_data( )[2].decode('ascii')).strip().split("\t")[1])
    battery_percentage = int(str(device._get_data( )[4].decode('ascii')).strip().split("\t")[1])/10

    battery_data = { 'draw' : power_usage, 'percentage' : battery_percentage, 'voltage' : volts }
    return jsonify(battery_data)

@app.route('/orange/mppt_info', methods=['GET'])
def get_mppt_data():
    mppt_device = vedirect.VEDirect("COM4")
    wh_used_today = int(str(mppt_device._get_data( )[12].decode('ascii')).strip().split("\t")[1]) * 10
    peak_charge_rate_today = int(str(mppt_device._get_data( )[13].decode('ascii')).strip().split("\t")[1])
    wh_used_yesterday = int(str(mppt_device._get_data( )[14].decode('ascii')).strip().split("\t")[1]) * 10
    peak_charge_rate_yesterday = int(str(mppt_device._get_data( )[15].decode('ascii')).strip().split("\t")[1])

    mppt_data = { 'current draw' :  mppt_device.solar_power, 'todays_wh' : wh_used_today, 'todays_peak' : peak_charge_rate_today, 'yesterdays_wh' : wh_used_yesterday, 'yesterdays_peak' : peak_charge_rate_yesterday }
    return jsonify(mppt_data)
# device = vedirect.VEDirect("COM3")
# volts = float(str(device._get_data( )[0].decode('ascii')).strip().split("\t")[1])/1000.0
# power_usage = int(str(device._get_data( )[2].decode('ascii')).strip().split("\t")[1])
# battery_percentage = int(str(device._get_data( )[4].decode('ascii')).strip().split("\t")[1])/10
# print("Battery Percent:", battery_percentage)
# print("Battery Voltage:", volts)
# print("Current Battery Draw:", power_usage, "watts")

# mppt_device = vedirect.VEDirect("COM4")
# kwh_used_today = int(str(mppt_device._get_data( )[12].decode('ascii')).strip().split("\t")[1]) * 10
# peak_charge_rate_today = int(str(mppt_device._get_data( )[13].decode('ascii')).strip().split("\t")[1])
# kwh_used_yesterday = int(str(mppt_device._get_data( )[14].decode('ascii')).strip().split("\t")[1]) * 10
# peak_charge_rate_yesterday = int(str(mppt_device._get_data( )[15].decode('ascii')).strip().split("\t")[1])
# print("Solar Power being used:", mppt_device.solar_power, "watts")
# print("Todays Generated Power:", kwh_used_today, "Wh")
# print("Todays Peak Charge Rate:", peak_charge_rate_today, "Wh")
# print("Yesterdayss Generated Power:", kwh_used_yesterday, "Wh")
# print("Yesterdays Peak Charge Rate:", peak_charge_rate_yesterday, "Wh")


if __name__ == '__main__':
   app.run(port=1099)