from flask import Flask
from flask import request
import sqlite3

app = Flask(__name__)
DEVICE_MANAGEMENT_DB = 'DeviceManagementDB.db'
SQL_ADD_DEVICE = 'INSERT into Device(DeviceQRCode,DeviceName,DeviceStatus) VALUES(?,?,?)'
sqliteConnection = None

@app.route("/")
def main():
    return "Welcome to Device Management Server!"

@app.route("/device")
def device():
    action = request.args.get('action')
    if action == 'add':
        try:
            #QR code should be generated by text template <RBVHINNO|||||DEVICENAME|||||STATUS>
            #Example: RBVHINNO|||||ESP 8266 {1}|||||AVAILABLE
            deviceQRCode = request.args.get('qr')
            deviceQRCodeStr = str(deviceQRCode)
            deviceName = (deviceQRCodeStr.split('|||||'))[1]
            deviceStatus = (deviceQRCodeStr.split('|||||'))[2]
            deviceItem = (deviceQRCodeStr, deviceName, deviceStatus)
            sqliteConnection = sqlite3.connect(DEVICE_MANAGEMENT_DB)
            cur = sqliteConnection.cursor()
            cur.execute(SQL_ADD_DEVICE, deviceItem)
            sqliteConnection.commit()
            cur.close()
            sqliteConnection.close()
            return "adding device - qr:" + deviceQRCodeStr + ", name: " + deviceName + ", status: " + deviceStatus
        except sqlite3.Error as error:
            return "Error SQLite: " + str(error)
        except Exception as e:
            return "Unexpected error:" + str(e)

    else:
        return "For device action!"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=7777)
