
import logging

import time

import datetime

import urllib.parse

import http.client

from influxdb import InfluxDBClient

from oko_user_config import *

oko_influxdb_query = "select temperature, humidity, light, windspeed, pressure from weather where device='%STATION%' order by time desc limit 1;"

def read_data_from_influxdb():
    # temp, hum, wind, pres, date
    ret = [ 0.0, 0.0, 0.0, 0.0, "" ]

    client = InfluxDBClient(oko_server, oko_server_port, oko_user, oko_password, oko_dbname)

    query = oko_influxdb_query.replace("%STATION%", oko_weatherstation_name)
    print(query)

    qres = client.query(query)
    print(qres)

    tdata = qres.raw['series'][0]['values'][0]

    print(tdata)

    ret[0] = tdata[1] # temp
    ret[1] = tdata[2] # hum
    ret[2] = tdata[4] * 1000 # wind km/h to m/s
    ret[3] = tdata[5] # pres
    ret[4] = tdata[0] # date

    print(ret)
    return ret

def send_data_to_openweather(temp, hum, wind, pres, date):

    # http://api.openweathermap.org/data/3.0/stations?appid=
    http.client.HTTPSConnection.debuglevel = 1
    conn = http.client.HTTPSConnection("api.openweathermap.org")

    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)
    requests_log = logging.getLogger("requests.packages.urllib3")
    requests_log.setLevel(logging.DEBUG)
    requests_log.propagate = True

    url = "/data/3.0/measurements?appid=" + openweather_api_key

    data = '[{"station_id":"' + openweather_station_id + '",' + \
             '"dt":' + str(date) + ',' + \
             '"temperature":' + str(temp) + ',' + \
             '"wind_speed":' + str(wind) + ',' + \
             '"pressure":' + str(pres) + ',' + \
             '"humidity":' + str(hum) + '' + \
           '}]'

    header = { "Content-Type" : "application/json" }

    print(url)
    print(data)
    print(header)

    #conn.request("POST", url, urllib.parse.urlencode(data), header)
    conn.request("POST", url, data, header)

    res = conn.getresponse()
    print(res.read())

def date_to_str(date):
    date = date.replace("T", " ")[0:19]
    ret = int(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").timetuple()))
    return ret

if __name__ == "__main__":

    data = [ 0.0, 0.0, 0.0, 0.0, 0 ]

    data = read_data_from_influxdb()

    temp = data[0]
    hum = data[1]
    wind = data[2]
    pres = data[3]
    date = data[4]

    tdate = date_to_str(date)

    send_data_to_openweather(temp, hum, wind, pres, tdate)

