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

from application.app import db
from models.device import DeviceModel
from models.monitorEvm import MonitorEvmModel
from models.monitorImage import MonitorImageModel
from models.monitorLvgl import MonitorLvglModel
from models.monitorSystem import MonitorSystemModel
from webcreator.log import logger

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

    def post(self, params):
        data = dict()
        for k in params:
            if hasattr(MonitorSystemModel, k):
                data[k] = params[k]
        result = MonitorSystemModel(**data)
        db.session.add(result)
        db.session.commit()
        return True

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

    def post(self, params):
        data = dict()
        for k in params:
            if hasattr(MonitorLvglModel, k):
                data[k] = params[k]
        result = MonitorLvglModel(**data)
        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):
        data = dict()
        for k in params:
            if hasattr(MonitorImageModel, k):
                data[k] = params[k]
        result = MonitorImageModel(**data)
        db.session.add(result)
        db.session.commit()
        return True

    def post_array(self, array, watch):
        t = []
        for a in array:
            data = dict()
            for k in a:
                if hasattr(MonitorImageModel, k):
                    data[k] = a[k]

            data.update({ "watch": watch })
            t.append(data)

        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
    device_id = -1
    if not msg.get("imei"):
        return None

    result = DeviceModel.query.filter(DeviceModel.imei==msg.get("imei")).one_or_none()
    if not result:
        return None

    device_id = result.id

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

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

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

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

    return True

def get_watch_list():
    result = DeviceModel.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 = DeviceModel.query.filter(DeviceModel.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)
        }
