import datetime
import time
import json
from datetime import datetime
from py_dotenv import read_dotenv
import os
import paramiko
import paho.mqtt.client as mqtt
import subprocess

from PIL import Image


read_dotenv("/home/orangepi/opencv/.env")
idsystem       =os.getenv("id")
directory_path =os.getenv("path_captures")

sftp_host     = os.getenv("ssh_host")
sftp_port     = int(os.getenv("ssh_port"))
sftp_username = os.getenv("ssh_user")
sftp_password = os.getenv("ssh_pass")


branding      = os.getenv("branding")

ignicion      = os.getenv("igni")
act_igni      = os.getenv("act_igni")


remote_directory = os.getenv("ssh_folder_path")+idsystem
fecha_systema=datetime.now().strftime("%Y-%m-%d")


def transfer():

    try:

        if act_igni=='off':
            if ignicion=='0':
                return

        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(sftp_host, username=sftp_username, password=sftp_password,port=sftp_port)
        stdin, stdout, stderr = ssh_client.exec_command(f"mkdir -p {remote_directory}/cam1/pictures/{fecha_systema}")
        #stdin, stdout, stderr = ssh_client.exec_command(f"mkdir -p {remote_directory}/cam3/pictures/{fecha_systema}")
        stdin, stdout, stderr = ssh_client.exec_command(f"mkdir -p {remote_directory}/cam5/pictures/{fecha_systema}")
        stdin, stdout, stderr = ssh_client.exec_command(f"mkdir -p {remote_directory}/cam7/pictures/{fecha_systema}")

        ssh_client.close()

        try:
            transport = paramiko.Transport((sftp_host, sftp_port))
            transport.sock.settimeout(1)
            transport.connect(username=sftp_username, password=sftp_password)

            sftp = paramiko.SFTPClient.from_transport(transport)

            channel=sftp.get_channel()
            channel.settimeout(10)

            datefilename=datetime.now().strftime("%Y%m%d%H%M")

            sftp.put("/home/orangepi/opencv/captures/cam1/last/5.jpg", remote_directory+f"/cam1/pictures/{fecha_systema}/{datefilename}.jpg")
            #sftp.put("/home/orangepi/opencv/captures/cam3/last/5.jpg", remote_directory+f"/cam3/pictures/{fecha_systema}/{datefilename}.jpg")
            sftp.put("/home/orangepi/opencv/captures/cam5/last/5.jpg", remote_directory+f"/cam5/pictures/{fecha_systema}/{datefilename}.jpg")
            sftp.put("/home/orangepi/opencv/captures/cam7/last/5.jpg", remote_directory+f"/cam7/pictures/{fecha_systema}/{datefilename}.jpg")


            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(sftp_host, username=sftp_username, password=sftp_password,port=sftp_port)
            stdin, stdout, stderr = ssh_client.exec_command(f"cp {remote_directory}/cam1/pictures/{fecha_systema}/{datefilename}.jpg {remote_directory}/cam1/pictures/last.jpg")
            #stdin, stdout, stderr = ssh_client.exec_command(f"cp {remote_directory}/cam3/pictures/{fecha_systema}/{datefilename}.jpg {remote_directory}/cam3/pictures/last.jpg")
            stdin, stdout, stderr = ssh_client.exec_command(f"cp {remote_directory}/cam5/pictures/{fecha_systema}/{datefilename}.jpg {remote_directory}/cam5/pictures/last.jpg")
            stdin, stdout, stderr = ssh_client.exec_command(f"cp {remote_directory}/cam7/pictures/{fecha_systema}/{datefilename}.jpg {remote_directory}/cam7/pictures/last.jpg")
            ssh_client.close()



        except socket.timeout:
            print("time out...")
            client.publish("mqttnubbe/cameras/status",json.dumps({"idsystem":idsystem,"lbl":"Problemas al establecer conexion de  streaming (timeout)","id":103}))
        except Exception as e:
            print("error transferencia")
            client.publish("mqttnubbe/cameras/status",json.dumps({"idsystem":idsystem,"lbl":"Error durante streaming","id":102}))
        finally:
            print("ffinaly")
            client.publish("mqttnubbe/cameras/status",json.dumps({"idsystem":idsystem,"lbl":"Termina  streaming","id":101}))


    except Exception as e:
        sftp.close()



if __name__ == "__main__":
    transfer()
