import sys
import os
import datetime
from peewee import *
import json

from utils.DBModels.BaseModel import BaseModel

sys.path.append('../')
sys.path.append('../../../')

class JSONField(TextField):
    def db_value(self, value):
        return json.dumps(value)

    def python_value(self, value):
        if value is not None:
            return json.loads(value)



class DeviceDB(BaseModel):
    deviceName = CharField()
    proType = CharField()
    masterSlaveModel = CharField()
    areaJson = JSONField()
    pvUpperLimit = CharField()
    pvLowerLimit = CharField()
    pvUnit = CharField()
    createTime = CharField()

    # 查询设备是否存在
    @classmethod
    def getByName(cls, deviceName):
        try:
            return cls.get(cls.deviceName == str(deviceName))
        except Exception as e:
            return 


    # 删除设备
    @classmethod
    def deleteDevice(cls, deviceName):
        try:
            query = cls.delete().where(cls.deviceName == deviceName)
            query.execute()
            return 'ok'
        except Exception as e:
            return 

    # 添加设备

    def addDevice(self, deviceName, proType, masterSlaveModel=masterSlaveModel, areaJson=json.dumps([]), pvUpperLimit=None, pvLowerLimit=None, pvUnit=None):
        self.deviceName = deviceName
        self.proType = proType
        self.masterSlaveModel = masterSlaveModel
        self.areaJson = areaJson
        self.pvUpperLimit = pvUpperLimit
        self.pvLowerLimit = pvLowerLimit
        self.pvUnit = pvUnit
        self.createTime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        # print(self.createTime)
        self.save()
    




