'''
Author: your name
Date: 2021-06-29 19:24:32
LastEditTime: 2021-07-12 12:09:34
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\controller\monitor.py
'''

from application.app import db
from models.monitorEvm import MonitorEvmModel
from models.monitorImage import MonitorImageModel
from models.monitorLvgl import MonitorLvglModel
from models.monitorSystem import MonitorSystemModel
from models.monitorWatch import MonitorWatchModel

class SystemResource(object):
    def get(self):
        return MonitorSystemModel.query.all()

    def post(self, params):
        result = MonitorSystemModel(**params)
        db.session.add(result)
        db.session.commit()
        return True

class LvglResource(object):
    def get(self):
        return MonitorLvglModel.query.all()

    def post(self, params):
        result = MonitorLvglModel(**params)
        db.session.add(result)
        db.session.commit()
        return True

class EvmResource(object):
    def get(self):
        return MonitorEvmModel.query.all()

    def post(self, params):
        result = MonitorEvmModel(**params)
        db.session.add(result)
        db.session.commit()
        return True

class ImageResource(object):
    def get(self):
        return MonitorImageModel.query.all()

    def post(self, params):
        result = MonitorImageModel(**params)
        db.session.add(result)
        db.session.commit()
        return True

    def post_array(self, array, watch):
        t = []
        for a in array:
            a.update({ "watch": watch })
            t.append(**a)

        db.session.execute(MonitorImageModel.__table__.insert(), t)
        db.session.commit()
        return True

systemResource = SystemResource()
lvglResource = LvglResource()
evmResource = EvmResource()
imageResource = ImageResource()

def insert_data(msg):
    # 先判断手表imei是否存在，不存在则先注册手表IMEI
    watch_id = -1
    if msg.get("imei"):
        result = MonitorWatchModel.query.filter_by(imei=msg.get("imei")).one_or_none()
        if result:
            watch_id = result.id
        else:
            result = MonitorWatchModel.query.filter(MonitorWatchModel.imei==msg.get("imei")).one_or_none()
            db.session.add(result)
            db.session.commit()
            watch_id = result.id

    if msg.get("system") or msg.get("request"):
        msg.get("system", {}).update({ "watch": watch_id })
        msg.get("system").update(msg.get("request", {}))
        systemResource.post(msg.get("system"))

    if msg.get("lvgl"):
        msg.get("lvgl").update({ "watch": watch_id })
        lvglResource.post(msg.get("lvgl"))

    if msg.get("evm"):
        msg.get("evm").update({ "watch": watch_id })
        evmResource.post(msg.get("evm"))

    if msg.get("image"):
        imageResource.post_array(msg.get("image"), watch_id)

def get_watch_list():
    result = MonitorWatchModel.query.all()
    tmp = []
    for item in result:
        tmp.append({
            'id': item.id,
            'imei': item.imei
        })
    return tmp

def evm_data(watch, start, end):
    filters = [MonitorEvmModel.watch==watch]
    if start:
        filters.append(MonitorEvmModel.timestamp >= start)
    if end:
        filters.append(MonitorEvmModel.timestamp <= end)
    result = MonitorEvmModel.query.filter(*filters).order_by(MonitorEvmModel.timestamp).all()
    temp = []
    for item in result:
        t = item.to_dict()
        if t.get("timestamp"):
            t.update({ 'timestamp': t.get("timestamp").strftime("%Y-%m-%d %H:%M:%S") })
        temp.append(t)

    return temp

def lvgl_data(watch, start, end):
    filters = [MonitorLvglModel.watch==watch]
    if start:
        filters.append(MonitorLvglModel.timestamp>=start)
    if end:
        filters.append(MonitorLvglModel.timestamp<=end)
    result = MonitorLvglModel.query.filter(*filters).order_by(MonitorLvglModel.timestamp).all()
    temp = []
    for item in result:
        t = item.to_dict()
        if t.get("timestamp"):
            t.update({ 'timestamp': t.get("timestamp").strftime("%Y-%m-%d %H:%M:%S") })
        temp.append(t)

    return temp

def image_data(watch, start, end):
    filters = [MonitorImageModel.watch==watch]
    if start:
        filters.append(MonitorImageModel.timestamp>=start)
    if end:
        filters.append(MonitorImageModel.timestamp<=end)
    result = MonitorImageModel.query.filter(*filters).order_by(MonitorImageModel.timestamp).all()
    temp = []
    for item in result:
        t = item.to_dict()
        if t.get("timestamp"):
            t.update({ 'timestamp': t.get("timestamp").strftime("%Y-%m-%d %H:%M:%S") })
        temp.append(t)

    return temp

def get_monitor_list(watch, category, start, end):
    # 判断watch是否存在
    w = MonitorWatchModel.query.filter(MonitorWatchModel.id==watch).first()
    if not w:
        return []

    if category == "system":
        return []
    elif category == "image":
        return image_data(watch, start, end)
    elif category == "lvgl":
        return lvgl_data(watch, start, end)
    elif category == "evm":
        return evm_data(watch, start, end)
    else:
        return {
            'evm': evm_data(watch, start, end),
            'lvgl': lvgl_data(watch, start, end),
            'image': image_data(watch, start, end)
        }
