import subprocess

class local_dir_remote:
    def __init__(self, config):
        self.config = config
        self.path = config["path"]

    def list_dir(self, recursive_search = False):
        path = Path(self.path)
        file_list = []
        delta = timedelta(minutes=2)
        glob_pattern = '*'
        glob_pattern_recursive = '**'
        if not recursive_search:
            #os.
            for file_demo in list(path.glob(glob_pattern)):
                mtime = datetime.fromtimestamp(os.stat(file_demo).st_mtime)
                if mtime < datetime.now() - delta:
                    file_list.append(file_demo)
        else:
            for file_directory in list(path.glob(glob_pattern_recursive)):
                try:
                    for files in list(file_directory.glob(glob_pattern)):
                        if '/maps' in str(files):
                            continue
                        file_list.append(files)
                except Exception:
                    continue
        return file_list

    def zip_local_directory(self, job):
        source_files = self.list_dir(True)
        zipname = f'{job["zipname"]}-{str(datetime.now()).split(" ")[0]}.tar.xz'
        #-T3 = 3 threads, the backups are meant to run in the night at 5 am to not interfere with players.
        exec_command_state = f"XZ_OPT='-T3 --memlimit-compress=70%' tar --exclude='/home/gameservers/.python_history' --exclude='/home/gameservers/fastdl' --exclude='/home/gameservers/.cache' --exclude='/home/gameservers/css_mg/cstrike/demos' --exclude='/home/gameservers/css_mg/cstrike/download' --exclude='/home/gameservers/css_mg/cstrike/addons/sourcemod/data' --exclude='/home/gameservers/css_jb/cstrike/logs' --exclude='/home/gameservers/css_jb/cstrike/download' --exclude='/home/gameservers/css_jb/cstrike/downloadlists' --exclude='/home/gameservers/css_ze/cstrike/download' --exclude='/home/gameservers/css_ze/cstrike/maps' --exclude='/home/gameservers/css_2_ze/cstrike/maps' --exclude='/home/gameservers/css_zr/cstrike/maps' --exclude='/home/gameservers/css_mg/cstrike/maps' --exclude='/home/gameservers/css_gg/cstrike/maps' --exclude='/home/gameservers/css_jb/cstrike/maps' --exclude='/home/gameservers/css_2_ze/cstrike/download' --exclude='/home/gameservers/css_dev/cstrike/download' --exclude='/home/gameservers/css_2_ze/cstrike/addons/sourcemod/data' --exclude='/home/gameservers/svencoop/svencoop/logs' --exclude='/home/gameservers/css_gg/cstrike/logs' --exclude='/home/gameservers/css_gg/cstrike/download' --exclude='/home/gameservers/css_gg/cstrike/downloadlists' --exclude='/home/gameservers/css_mg_dev/cstrike/demos' --exclude='/home/gameservers/css_mg_dev/cstrike/download' --exclude='/home/gameservers/css_zr/cstrike/download' --exclude='/home/gameservers/hl2_synergy' --exclude='/home/gameservers/svencoop/svencoop_addon/maps' --ignore-failed-read -cJf {zipname} {self.path}"
        print("exec_command_state: ", exec_command_state)
        subprocess.run([exec_command_state], shell=True)

        return str(Path.cwd()) + '/' +  zipname

    def delete_local_demo(self, pathfile):
        with contextlib.suppress(FileNotFoundError):
            if str(pathfile).endswith('.dem'):
                os.remove(pathfile)
                print('removed demo: ', pathfile)

    def delete_local_zip(self, zip_file_path):
        with contextlib.suppress(FileNotFoundError):
            if (str(zip_file_path).endswith('.tar.xz')):
                os.remove(zip_file_path)
                print('removed tar xz: ', zip_file_path)

