from datetime import datetime
import os, base64, json

os.makedirs(os.path.join('static', 'face'), 0o777, True)
os.makedirs(os.path.join('static', 'person'), 0o777, True)
os.makedirs(os.path.join('static', 'background'), 0o777, True)

class DeviceInfo(object):
    def __init__(self, json):
        # self.DeviceId   = json['DeviceId']   if 'DeviceId'   in json else ""
        self.DeviceUUID   = json['DeviceUUID'] if 'DeviceUUID' in json else ""
        # self.DeviceMac  = json['DeviceMac']  if 'DeviceMac'  in json else ""
        self.DeviceIp     = json['DeviceIp']   if 'DeviceIp'   in json else ""
        # self.ChannelNo  = json['ChannelNo']  if 'ChannelNo'  in json else ""
        # self.DeviceMode = json['DeviceMode'] if 'DeviceMode' in json else ""
        self.Unused = {
            'DeviceId': json['DeviceId']     if 'DeviceId'   in json else "",
            'DeviceMac': json['DeviceMac']   if 'DeviceMac'  in json else "",
            'ChannelNo': json['ChannelNo']   if 'ChannelNo'  in json else "",
            'DeviceMode': json['DeviceMode'] if 'DeviceMode' in json else "",
        }
class CaptureInfo(object):
    def __init__(self, json):
        if 'SendTime' in json and len(json['SendTime']) > 0:
            self.SendTime = datetime.strptime(json['SendTime'], '%Y-%m-%d %H:%M:%S')
        else:
            self.SendTime = None
        if 'CaptureTime' in json and len(json['CaptureTime']) > 0:
            self.CaptureTime = datetime.strptime(json['CaptureTime'], '%Y-%m-%d %H:%M:%S')
        else:
            self.CaptureTime = None
        self.CaptureCount      = json['CaptureCount']      if 'CaptureCount'      in json else ""
        # self.RecordId        = json['RecordId']          if 'RecordId'          in json else ""
        self.FacePicture       = json['FacePicture']       if 'FacePicture'       in json else ""
        self.BackgroundPicture = json['BackgroundPicture'] if 'BackgroundPicture' in json else ""
        self.Unused = {
            'RecordId': json['RecordId'] if 'RecordId' in json else "",
        }
    def SaveFace(self, name):
        file = '{0}.jpg'.format(os.path.join('static', 'face', name))
        if not os.path.isfile(file) and len(self.FacePicture) > 0:
            with open(file, 'wb') as f:
                f.write(base64.b64decode(self.FacePicture))
        self.FacePicture = file
        return True
    def SaveBackground(self, name):
        file = '{0}.jpg'.format(os.path.join('static', 'background', name))
        if not os.path.isfile(file) and len(self.BackgroundPicture) > 0:
            with open(file, 'wb') as f:
                f.write(base64.b64decode(self.BackgroundPicture))
        self.BackgroundPicture = file
        return True
class FaceInfo(object):
    def __init__(self, json):
        self.FaceId        = json['FaceId']                  if 'FaceId'       in json else ""
        # self.FaceQuality = json['FaceQuality']             if 'FaceQuality'  in json else ""
        self.FacePosition  = json['FacePosition'].split(',') if 'FacePosition' in json else []
        self.Unused = {
            'FaceQuality': json['FaceQuality'] if 'FaceQuality' in json else "",
        }
class CompareInfo(object):
    def __init__(self, json):
        # self.AlarmEvent = json['AlarmEvent']             if 'AlarmEvent'  in json else ""
        # self.Liveness   = json['Liveness']               if 'Liveness'    in json else ""
        if 'CompareTime' in json and len(json['CompareTime']) > 0:
            self.CompareTime = datetime.strptime(json['CompareTime'], '%Y-%m-%d %H:%M:%S')
        else:
            self.CompareTime = None
        self.PersonType = json['PersonType']               if 'PersonType'  in json else ""
        self.VisitsCount  = int(json['VisitsCount'])       if 'VisitsCount' in json else 0
        self.Similarity   = float(json['Similarity'])      if 'Similarity'  in json else 0.0
        self.PersonInfo   = PersonInfo(json['PersonInfo']) if 'PersonInfo'  in json else None
        self.Unused = {
            'AlarmEvent': json['AlarmEvent'] if 'AlarmEvent' in json else "",
            'Liveness': json['Liveness']     if 'Liveness'   in json else "",
            # 'PersonType': json['PersonType'] if 'PersonType' in json else "",
        }
class PersonInfo(object):
    def __init__(self, json):
        self.PersonId        = json['PersonId']                         if 'PersonId'        in json else ""
        self.PersonName      = json['PersonName']                       if 'PersonName'      in json else ""
        self.Sex             = json['Sex']                              if 'Sex'             in json else 0
        # self.IDCard        = json['IDCard']                           if 'IDCard'          in json else None
        # self.Nation        = json['Nation']                           if 'Nation'          in json else None
        # self.Birthday      = json['Birthday']                         if 'Birthday'        in json else None
        # self.Phone         = json['Phone']                            if 'Phone'           in json else None
        # self.Address       = json['Address']                          if 'Address'         in json else None
        # self.SaveTime      = datetime.strptime(json['SaveTime'], '%Y-%m-%d %H:%M:%S')
        if 'LimitTime' in json:
            # print(json['LimitTime'])
            self.LimitTime = json['LimitTime']
        else:
            self.LimitTime = None
        if 'StartTime' in json and len(json['StartTime']) > 0:
            # print(json['StartTime'])
            self.StartTime = datetime.strptime(json['StartTime'], '%Y-%m-%d %H:%M:%S')
        else:
            self.StartTime = None
        if 'EndTime' in json and len(json['EndTime']) > 0:
            # print(json['EndTime'])
            self.EndTime = datetime.strptime(json['EndTime'], '%Y-%m-%d %H:%M:%S')
        else:
            self.EndTime = None
        # self.Label         = json['Label']                            if 'Label'           in json else None
        self.PersonExtension = PersonExtension(json['PersonExtension']) if 'PersonExtension' in json else None
        self.PersonPhoto     = json['PersonPhoto']                      if 'PersonPhoto'     in json else ""
        self.Unused = {
            'IDCard': json['IDCard']     if 'IDCard'   in json else "",
            'Nation': json['Nation']     if 'Nation'   in json else "",
            'Birthday': json['Birthday'] if 'Birthday' in json else "",
            'Phone': json['Phone']       if 'Phone'    in json else "",
            'Address': json['Address']   if 'Address'  in json else "",
            'SaveTime': json['SaveTime'] if 'SaveTime' in json else "",
            'Label': json['Label']       if 'Label'    in json else "",
        }
    def SavePerson(self):
        file = '{0}.jpg'.format(os.path.join('static', 'person', self.PersonId))
        if not os.path.isfile(file) and len(self.PersonPhoto) > 0:
            with open(file, 'wb') as f:
                f.write(base64.b64decode(self.PersonPhoto))
            self.PersonPhoto = file
        return True
class PersonExtension(object):
    def __init__(self, json):
        # self.PersonCode1       = json['PersonCode1']       if 'PersonCode1' in json else None
        # self.PersonCode2       = json['PersonCode2']       if 'PersonCode2' in json else None
        # self.PersonCode3       = json['PersonCode3']       if 'PersonCode3' in json else None
        # self.PersonReserveName = json['PersonReserveName'] if 'PersonReserveName' in json else None
        # self.PersonParam1      = json['PersonParam1']      if 'PersonParam1' in json else None
        # self.PersonParam2      = json['PersonParam2']      if 'PersonParam2' in json else None
        # self.PersonParam3      = json['PersonParam3']      if 'PersonParam3' in json else None
        # self.PersonParam4      = json['PersonParam4']      if 'PersonParam4' in json else None
        # self.PersonParam5      = json['PersonParam5']      if 'PersonParam5' in json else None
        # self.PersonData1       = json['PersonData1']       if 'PersonData1' in json else None
        # self.PersonData2       = json['PersonData2']       if 'PersonData2' in json else None
        # self.PersonData3       = json['PersonData3']       if 'PersonData3' in json else None
        # self.PersonData4       = json['PersonData4']       if 'PersonData4' in json else None
        # self.PersonData5       = json['PersonData5']       if 'PersonData5' in json else None
        self.Unused = {
            'PersonCode1': json['PersonCode1']             if 'PersonCode1'       in json else "",
            'PersonCode2': json['PersonCode2']             if 'PersonCode2'       in json else "",
            'PersonCode3': json['PersonCode3']             if 'PersonCode3'       in json else "",
            'PersonReserveName': json['PersonReserveName'] if 'PersonReserveName' in json else "",
            'PersonParam1': json['PersonParam1']           if 'PersonParam1'      in json else "",
            'PersonParam2': json['PersonParam2']           if 'PersonParam2'      in json else "",
            'PersonParam3': json['PersonParam3']           if 'PersonParam3'      in json else "",
            'PersonParam4': json['PersonParam4']           if 'PersonParam4'      in json else "",
            'PersonParam5': json['PersonParam5']           if 'PersonParam5'      in json else "",
            'PersonData1': json['PersonData1']             if 'PersonData1'       in json else "",
            'PersonData2': json['PersonData2']             if 'PersonData2'       in json else "",
            'PersonData3': json['PersonData3']             if 'PersonData3'       in json else "",
            'PersonData4': json['PersonData4']             if 'PersonData4'       in json else "",
            'PersonData5': json['PersonData5']             if 'PersonData5'       in json else "",
        }
class TemperaInfo(object):
    def __init__(self, json):
        self.Temperature        = float(json['Temperature'])      if 'Temperature'      in json else 0.0
        # self.EnvirTemperature = float(json['EnvirTemperature']) if 'EnvirTemperature' in json else None
        self.Unused = {
            'EnvirTemperature': json['EnvirTemperature'] if 'EnvirTemperature' in json else "",
        }
class PunchCardModel(object):
    def __init__(self):
        now = datetime.now()
        self.ID = int(datetime.timestamp(datetime.now()))
        self.Name = "unknown"
        self.TimeStamp = int(datetime.timestamp(now))
        self.ResultCode = 0
    def SetData(self, data):
        data = data.replace("\'", "\"")
        data = json.loads(data)
        c1 = self.SetDevice(data['DeviceInfo']) if 'DeviceInfo' in data else False
        c2 = self.SetCapture(data['CaptureInfo']) if 'CaptureInfo' in data else False
        c3 = self.SetFace(data['FaceInfo']) if 'FaceInfo' in data else False
        c4 = self.SetCompare(data['CompareInfo']) if 'CompareInfo' in data else False
        c5 = self.SetTimpera(data['TemperaInfo']) if 'TemperaInfo' in data else False
        if c1 and c2 and c3 and c4 and c5:
            if self.CompareInfo.PersonInfo is None:
                c6 = True
            else:
                self.ID = self.CompareInfo.PersonInfo.PersonId
                self.Name = self.CompareInfo.PersonInfo.PersonName
                c6 = self.CompareInfo.PersonInfo.SavePerson()
            filename = '{0}_{1}'.format(self.ID, self.CaptureInfo.CaptureTime.strftime('%Y_%m_%d_%H_%M_%S'))
            c7 = self.CaptureInfo.SaveFace(filename)
            c8 = self.CaptureInfo.SaveBackground(filename)
            if c6 and c7 and c8:
                self.ResultCode = 1
                return True
            elif not c6:
                print("save face image failed")
            elif not c7:
                print("save background image failed")
            elif not c8:
                print("save person image failed")
        elif not c1:
            print("miss device info data")
        elif not c2:
            print("miss capture info data")
        elif not c3:
            print("miss face info data")
        elif not c4:
            print("miss compare info data")
        elif not c5:
            print("miss timperature info data")
        self.Unused = {}
        return False
    def SetDevice(self, data):
        try:
            self.DeviceInfo = DeviceInfo(data)
            return True
        except:
            return False
    def SetCapture(self, data):
        try:
            self.CaptureInfo = CaptureInfo(data)
            return True
        except:
            return False
    def SetFace(self, data):
        try:
            self.FaceInfo = FaceInfo(data)
            return True
        except:
            return False
    def SetCompare(self, data):
        try:
            self.CompareInfo = CompareInfo(data)
            return True
        except:
            return False
    def SetTimpera(self, data):
        try:
            self.TemperaInfo = TemperaInfo(data)
            return True
        except:
            return False
    def SetTimeStamp(self, timestamp):
        self.TimeStamp = int(timestamp)
    def GetDUUID(self):
        return self.DeviceInfo.DeviceUUID
    def GetID(self):
        return self.ID
    def GetHost(self):
        return self.DeviceInfo.DeviceIp
    def GetTime(self):
        return self.CaptureInfo.CaptureTime
    def GetName(self):
        return self.Name
    def GetType(self):
        return self.CompareInfo.PersonType
    def GetSimilarity(self):
        return self.CompareInfo.Similarity
    def GetTemperature(self):
        return self.TemperaInfo.Temperature
    def GetPosition(self):
        return self.FaceInfo.FacePosition
    def GetImagePath(self):
        return self.CaptureInfo.FacePicture
    def GetResponse(self):
        result = {
            'Name': 'captureInfoResponse',
            'TimeStamp': self.TimeStamp,
            'Session': '',
            'Code': self.ResultCode,
            'Message': '',
        }
        return result