
# A lambda function to interact with AWS RDS MySQL

import pymysql
import sys
import json
import time
from datetime import datetime, timedelta

REGION = 'eu-central-1'


rds_host  = "appychip.c27pqrom9fwo.eu-central-1.rds.amazonaws.com"
name = "appychip"
password = "appychip"
db_name = "appychip"

def save_events(event):
    """
    This function fetches content from mysql RDS instance
    """
    item_count = 0
    conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
   
   
    mycursor = conn.cursor()

    y = event['body-json']['data']
    b = y.find("data")
    b = b + 7
    c = y.find("\"",b,len(y))
    a = y[b]
    data = y[b:c]
    datalen = len(data)
    print(data)
    
    #datetime
    l = y.find("ts")
    l = l + 4
    l1 = y.find("\"", l, len(y))
    ts = y[l:l1-1]
    stime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime((int(ts))/1000))
    print(time.gmtime((int(ts))/1000))
    
    #EUI
    e1 = y.find("EUI") 
    e1 = e1 + 6
    e2 = y.find("\"", e1, len(y))
    eui = y[e1:e2]
    
    

    #for x in myresult:
    #    print(x)
        
    sql = "INSERT INTO iot_devices (eui, temp, humd, pres, dtime) VALUES (%s, %s, %s, %s, %s)"
    count = 0
    for i in range(0, datalen/12):
        temp = data[i+count:i+count+4]
        humd = data[i+count+4:i+count+8]
        pres = data[i+count+8:i+count+12]
        count = count + 11
        stime1 = datetime.strptime(stime, '%Y-%m-%d %H:%M:%S') + timedelta(minutes=1*i,hours=2)
        val = (eui, temp, humd, pres, stime1)
        mycursor.execute(sql, val)
        conn.commit()
        
    return stime

   



def main(event, context):
    #save_events(event)
    return {"statusCode": 250,
        "body": save_events(event),
        "headers": {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Methods': '*',
            'Access-Control-Allow-Origin': '*'
        }
    }  




