#Created by Vasilev.link. For WebControl purpose only
#!/usr/bin/python
#import paho.mqtt.client as paho, glob, os, json, sys, ssl
modules = ['pika','glob','os','json','base64','sys','ssl','requests','urllib','time','pi_switch']
dir_path = "/var/webcontrol"
headers = {
    'User-Agent': 'Webcontrol User Agent 1.0',
}
jsonheaders ={
    'User-Agent': 'Webcontrol User Agent 1.0',
    'Content-type': 'application/json', 
    'Accept': 'text/plain'
}
for module in modules:
   try:
     globals()[module] = __import__(module)
   except:
     print time.strftime("%Y-%m-%d %H:%M:%S")+": module "+module+" not imported! Please install it."
from xml.etree import ElementTree as ET
from Crypto.Cipher import AES
try:
  import pifacedigitalio as p
  p.init()
  checkpiface=1
except:
  checkpiface=0

class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
sys.stdout = Logger(dir_path+"/logs/webcontrol.log")

if checkpiface==1:
    if os.path.exists(dir_path+"/iotadmin_reset.json"):
        print time.strftime("%Y-%m-%d %H:%M:%S")+": loading iotadmin_reset.json file"
    else:
        f = open(dir_path+"/iotadmin_reset.json", 'a+')
        json.dump({}, f)
        f.close()

def getVarFromFile(filename):
    import imp
    f = open(filename)
    global conf
    conf = imp.load_source('conf', '', f)
    f.close()
getVarFromFile(dir_path+'/webconfig.conf')
mqtthost = conf.mqtthost
mqttuser = conf.mqttuser
mqttpass = conf.mqttpass
mqtttopic = conf.mqtttopic
mqtttstatus = conf.mqtttstatus
thisserver = mqtttopic
mqttclientid = conf.mqttclientid
webcontroluser = conf.webcontroluser
webuid = conf.webuid
uid=conf.security_uid
key=conf.security_key

AES.key_size=128
def decryptmess(mess):
    crypt_object=AES.new(key=key,mode=AES.MODE_CBC,IV=uid)
    decoded=base64.b64decode(str(mess))
    decrypted=crypt_object.decrypt(decoded)
    mess_data=json.loads(decrypted.replace('\0',''))
    return mess_data
