#!/usr/bin/env python3

import socket
from datetime import datetime
from time import sleep
from util import fprint

"""

from: https://github.com/MoisesBrito31/ve_data_log/blob/main/serverContagem/VE/drive.py
(no license)

(partially) adapted to English language & iVu camera instead of classic VE by Cole Deck

"""

def gravaLog(ip="1",tipo="Evento", msg="", file="log_imagem.txt"):
    # removed full logging
    fprint(msg)

class DriveImg():
    HEADERSIZE = 100
    ip = "192.168.0.1"
    port = 32200
    onLine = False

    def __init__(self, ip, port, pasta = "media/"):
        self.pasta = pasta
        self.ip=ip
        self.port = port
        self.trans = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.trans.settimeout(5)
        fprint("Trying to connect...")
        try:
            self.trans.connect((self.ip,self.port))
            self.onLine = True
            fprint("Camera Online")
            #self.trans.close()
        except:
            self.onLine = False 
            fprint("Offline")

    def read_img(self):
        resposta = 'Falha'
        try:
            if not self.onLine:
                #print(f'tentando Conectar camera {self.ip}...')
                gravaLog(ip=self.ip,msg=f'Trying to connect...')
                sleep(2)
                try:
                    self.trans = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                    self.trans.connect((self.ip,self.PORT))
                    self.onLine = True
                    gravaLog(ip=self.ip,msg=f'Connection established.')
                except:
                    self.onLine = False
                    self.trans.close()
                    return resposta
            ret = self.trans.recv(64)
            try:
                valida = str(ret[0:15].decode('UTF-8'))
                #print(valida)
                if valida.find("TC IMAGE")<0:
                    self.onLine = False
                    self.trans.close()
                    sleep(2)
                    gravaLog(ip=self.ip,tipo="Falha",msg=f'Unable to find TC IMAGE bookmark')
                    return "Error"
            except Exception as ex:
                self.onLine = False
                self.trans.close()
                sleep(2)
                gravaLog(ip=self.ip,tipo="Falha",msg=f'Error - {str(ex)}')
                return "Error"
            if ret:
                frame = int.from_bytes(ret[24:27],"little")
                isJpeg = int.from_bytes(ret[32:33],"little")
                img_size = int.from_bytes(ret[20:23],"little")
                data = self.trans.recv(5000)
                while img_size>len(data) and ret:
                    ret = self.trans.recv(10000)
                    if ret:
                        data = data+ret
                        #print(f'{len(ret)}b dados recebidos, total de: {len(data)+64}b')
                    else:
                        gravaLog(ip=self.ip,tipo="Falha",msg="Unable to recieve the image")
                        self.onLine = False
                        return "Unable to recieve the image"
                hoje = datetime.now()
                idcam = self.ip.split('.')
                """try:
                    nomeFile = f'{hoje.day}{hoje.month}{hoje.year}-{idcam[3]}-{frame}'
                    if isJpeg==1:
                        file = open(f'{self.pasta}{nomeFile}.jpg','wb')
                        nomeFile = f'{nomeFile}.jpg'
                    else:
                        file = open(f'{self.pasta}{nomeFile}.bmp','wb')
                        nomeFile = f'{nomeFile}.bmp'
                    file.write(data)
                    file.close()
                except Exception as ex:
                    sleep(2)
                    gravaLog(ip=self.ip,tipo="Falha",msg=f'Error - {str(ex)}')
                    return "Falha" 
                    """
                if isJpeg==1:
                    return "jpeg",data
                else:
                    return "bmp",data
                
        except Exception as ex:
            gravaLog(ip=self.ip,tipo="Falha Generica",msg=f'Error - {str(ex)}')
            #print(f'erro {str(ex)}')
            self.onLine = False
            self.trans.close()
            sleep(2)
            return resposta

class DriveData():
    HEADERSIZE = 100
    ip = "192.168.0.1"
    port = 32100
    onLine = False

    def __init__(self, ip, port):
        gravaLog(ip=self.ip,msg=f'iniciou drive',file="log_data.txt")
        self.ip=ip
        self.port = port
        self.trans = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        try:
            self.trans.connect((self.ip,self.port))
            self.onLine = True
        except:
            self.onLine = False 

    def read_data(self):
        resposta = 'falha'
        try:
            if not self.onLine:
                #print(f'tentando Conectar...\n')
                gravaLog(ip=self.ip,msg=f'tentando Conectar...',file="log_data.txt")
                sleep(2)
                try:
                    self.trans = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                    self.trans.connect((self.ip,self.PORT))
                    self.onLine = True
                    gravaLog(ip=self.ip,msg=f'Conexão restabelecida...',file="log_data.txt")
                except:
                    self.onLine = False
                    return resposta
            resposta = self.trans.recv(self.HEADERSIZE).decode("utf-8")
            resposta = str(resposta).split(',')
            return resposta
        except Exception as ex:
            self.onLine = False 
            gravaLog(ip=self.ip,tipo="Falha Generica",msg=f'erro {str(ex)}',file="log_data.txt")
            sleep(2)
            return resposta


if __name__ == "__main__":
    test = DriveImg("192.168.1.125", 32200)
    x = 0
    while x < 100:
        x=x+1
        imgtype, img = test.read_img()