#!/usr/bin/python
#-*- coding:utf8 -*-
#
# @author Peer Janssen
# @author Justin Otherguy <justin@justinotherguy.org>
# @author Henrik Wellschmidt <w3llschmidt@gmail.com>
# @copyright Copyright (c) 2011-2020, The volkszaehler.org project
# @license https://www.gnu.org/licenses/gpl-3.0.txt GNU General Public License version 3
#
#/*
#* This file is part of volkzaehler.org
#*
#* volkzaehler.org is free software: you can redistribute it and/or modify
#* it under the terms of the GNU General Public License as published by
#* the Free Software Foundation, either version 3 of the License, or
#* any later version.
#*
#* volkzaehler.org is distributed in the hope that it will be useful,
#* but WITHOUT ANY WARRANTY; without even the implied warranty of
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#* GNU General Public License for more details.
#*
#* You should have received a copy of the GNU General Public License
#* along with volkszaehler.org. If not, see <http://www.gnu.org/licenses/>.
#*/

from __future__ import division

import sys
import argparse
import datetime
import urllib2
import json

#----<config>-------------------------------------------------------------

middleware = 'http://demo.volkszaehler.org/middleware.php/'

tz_offset = 2 # h; CEST -> 2; CET -> 1; show me, how to improve this! :-)

#------------------------------------------------------------------------

parser = argparse.ArgumentParser(
prog='cALERT',
description='Configure cALERT at the commandline ->',
epilog="cALERT is intended to operate as a cronjob and monitors the cost (Power/Gas consumption) for a particular UUID, based on the configured costs of the channel and the consumption within the interval."
)

parser.add_argument("-u",dest="uuid", required=True, help="Enter the coresponding UUID here [required]")
parser.add_argument("-c",dest="costs", type=float, default=0, help="Cost limit that will cause a alert")
parser.add_argument("-i",dest="interval",  type=int, default=86400, help="Monitoring interval in seconds")

args = parser.parse_args()

uuid = args.uuid
maximum_value = args.costs
interval = args.interval

def timestamp2vz_format(ts):
  tz_delta = datetime.timedelta(seconds=tz_offset*3600) #UTC offset and adjustment for daylight saving time (sutraction in seconds)
  dt = ts - datetime.datetime(1970, 1, 1, 0, 0) - tz_delta
  Timestamp = str(dt.days*86400 + dt.seconds) + str(dt.microseconds).zfill(6)[:-3]
  return Timestamp

now = datetime.datetime.now()
past = now  - datetime.timedelta(seconds=interval)
intervalstart = timestamp2vz_format(past)

url_cost = middleware
url_cost += 'channel/'
url_cost += uuid
url_cost += '.json'

cost = urllib2.urlopen(url_cost).read()
json_decoded = json.loads(cost)
rate = json_decoded['entity']['cost']
type = json_decoded['entity']['type']
resolution = json_decoded['entity']['resolution']

url_data = middleware
url_data += 'data/'
url_data += uuid
url_data += '.json?from='
url_data += intervalstart

result = urllib2.urlopen(url_data).read()
json_decoded = json.loads(result)
consumption = json_decoded['data']['consumption']

if "power" in type:
	unit = "kWh"
	kosten = consumption * rate
	if kosten > maximum_value:
		print '%.2f%s / %.2fEUR' % (consumption / 1000, unit, kosten)

if "gas" in type:
	unit = "m3"
	kosten = consumption * rate
	if kosten > maximum_value:
		print '%.2f%s / %.2fEUR' % (consumption, unit, kosten)

sys.exit(-1)
