 # -*- coding:UTF-8 -*-

import json
import os
import datetime
import time
import shutil

class RaNas:

    def __init__(self, Components):
        """
        Initialisiert das RaNas

        :param Components: RaComponents Element
        :type Components: RaComponents
        """
        self.components = Components
        self.config = self.load_json("config.json")

    def load_json(self, filename):
        """
        Lädt die Menüstruktur aus einer JSON-Datei.
        
        :param filename: Der Name der JSON-Datei.
        """
        res=dict()
        with open(filename, "r") as file:
            res = json.load(file)  # Menüstruktur aus JSON laden
        return res

    def Sync(self):

        self.components.Menu.Progress(-1)
        self.MountNas()
        
        path = self.config["recording"]["dir"]
        files = list()
        filesizeTotal=0
        for filename in os.listdir(path):
            f = os.path.join(path, filename)
            t = os.path.getmtime(f)
            dt = datetime.datetime.fromtimestamp(t)
            year,month,day,hour,minute,second = time.localtime(dt)[:-3]
            filesize = os.path.getsize(f)

            mp4Exists = False
            rawExists = False

            mp4Path = self.config["nas"]["remote_path"]+"/Video/"+str(year)+"-"+str(month)+"-"+str(day)+"/"+filename[:-4]+"mp4"
            rawPath = self.config["nas"]["remote_path"]+"/Raw/"+str(year)+"-"+str(month)+"-"+str(day)+"/"+filename

            if self.config["nas"]["copy_raw"]==True:
                if os.path.exists(rawPath)==True:
                    rawExists = True
            else:
                rawExists = True
            if self.config["nas"]["copy_mp4"]==True:
                if os.path.exists(mp4Path)==True:
                    mp4Exists = True
            else:
                mp4Exists = True

            if mp4Exists==False or rawExists==False:
                files.append({
                    "Souce_path":f,
                    "size":filesize,
                    "date":dt,

                    "Raw_filename":filename,
                    "Mp4_targetname": filename[:-4]+"mp4",
                    "Mp4_targetpath": mp4Path,
                    "Raw_targetpath": rawPath,
                    "Mp4_subdir":self.config["nas"]["remote_path"]+"/Video/"+str(year)+"-"+str(month)+"-"+str(day),
                    "Raw_subdir":self.config["nas"]["remote_path"]+"/Raw/"+str(year)+"-"+str(month)+"-"+str(day)
                })
                filesizeTotal+=filesize


        FileIndex = 0
        FileLength = len(files)
        CopiedSize = 0
        fps = 30
        if "fps" in self.config["recording"] and isinstance(self.config["recording"]["fps"], int):
            fps = self.config["recording"]["fps"]

        # Create Base Dir
        if self.config["nas"]["copy_raw"]==True and os.path.exists(self.config["nas"]["remote_path"]+"/Raw")==False:
            os.mkdir(self.config["nas"]["remote_path"]+"/Raw")
        if self.config["nas"]["copy_raw"]==True and os.path.exists(self.config["nas"]["remote_path"]+"/Video")==False:
            os.mkdir(self.config["nas"]["remote_path"]+"/Video")
        if self.config["nas"]["copy_scans"]==True and os.path.exists(self.config["nas"]["remote_path"]+"/Scans")==False:
            os.mkdir(self.config["nas"]["remote_path"]+"/Scans")


        self.components.Menu.Progress(0)
        for itm in files.items():
            # Copy Raw
            if self.config["nas"]["copy_raw"]==True:
                if os.path.exists(itm["Raw_subdir"])==False:
                    os.mkdir(itm["Raw_subdir"])
                if os.path.exists(itm["Raw_targetpath"])==True:
                    shutil.copyfile(itm["Souce_path"], itm["Raw_targetpath"])

            # Convert mp4 and Copy
            if self.config["nas"]["copy_raw"]==True:
                if os.path.exists(itm["Raw_subdir"])==False:
                    os.mkdir(itm["Raw_subdir"])
                if os.path.exists(itm["Raw_targetpath"])==True:
                    self.SudoCmd("MP4Box -fps "+fps+" -add '"+itm["path"]+"' '"+itm["targetpath"]+"'")
                    
            # Delete File
            if self.config["nas"]["delete_after_sync"]==True:
                os.remove(itm["Souce_path"])

            FileIndex+=1
            CopiedSize+=os.path.getsize(f)
            #self.components.Menu.Progress((FileIndex*100)/FileLength)
            self.components.Menu.Progress((CopiedSize*100)/filesizeTotal)

        self.UnmountNas()
        self.components.Menu.StopProgress()


    def Ping(self):
        hostname = self.config["nas"]["address"]
        response = os.system("ping -c 1 " + hostname)
        if response == 0:
            return True
        else:
            return False

    def checkSudo(self):
        """
        Überprüft, ob der Benutzer Sudo-Rechte besitzt

        :ret: bool
        """
        if 'SUDO_UID' in os.environ.keys() or os.geteuid() == 0:
            return True
        else:
            pass # TODO: chekc für Sudo-Test Befehl akzeptiert
        return False

    def SudoCmd(self, command):
        """
        Führt einen Sudo Befehl aus.
        """
        from subprocess import PIPE, run
        if 'SUDO_UID' in os.environ.keys() or os.geteuid() == 0:
            result = run(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
            print(result.returncode, result.stdout, result.stderr)
        elif "sudo" in self.config["system"]:
            if self.config["system"]["sudo"]!=None and isinstance(self.config["system"]["sudo"], str) and self.config["system"]["sudo"]!="":
                result = run("echo "+self.config["system"]["sudo"]+" | sudo -S "+command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
                print(result.returncode, result.stdout, result.stderr)
        

    def MountNas(self):
        if self.Ping()==False:
            print("Failed to Mount. Could not ping NAS")
            return False

        if self.checkSudo()==False:
            print("Failed to Mount. Missing permission for '"+self.config["nas"]["local_path"]+"'")
            return False

        if os.path.isdir(self.config["nas"]["local_path"]) == False:
            self.SudoCmd("mkdir "+self.config["nas"]["local_path"])

        # sudo mount -n -w -t cifs //192.168.1.2/freigabe /media/freigabe -o user=pi,pass=raspberry
        self.SudoCmd("mount -n -w -t cifs //"+self.config["nas"]["address"]+self.config["nas"]["remote_path"]+" "+self.config["nas"]["local_path"]+" -o user="+self.config["nas"]["username"]+",pass="+self.config["nas"]["password"])

    def UnmountNas(self):
        self.SudoCmd("unmount //"+self.config["nas"]["address"]+self.config["nas"]["remote_path"])

