import os
import tempfile 
import pathlib as p
import subprocess
class FilMan:
    def __init__(self,name):
        self.name = name
        self.form={}

    def FileRead(self,path):
        file_content=""
        if os.path.isfile(path):
            with open(path,"r") as f:
                file_content= f.read()
        return file_content
    def WriteToFile(self,text,path):
        if not os.path.isfile(path):
            return None # Or handle error

        # 1. Create a temporary file in the same dire>
        dir_name = os.path.dirname(path)
        fd, temp_path = tempfile.mkstemp(dir=dir_name,
        text=True)

        try:
            with os.fdopen(fd, 'w') as tmp:
                tmp.write(text)
                tmp.flush()
                os.fsync(tmp.fileno()) # Forces the O>

            # 2. Atomic Rename: This replaces the old>
            # Even if the server crashes now, the old>
            os.replace(temp_path, path)

        except Exception as e:
            if os.path.exists(temp_path):
                os.remove(temp_path)
            raise e
        return text
    def File_Struct(self,dirs):
        file_struct={}
        a=p.Path(dirs)
        if a.is_file():
            file_struct[a.name]=a.name
        elif a.is_dir():
            for i in a.iterdir():
                file_struct[i.name]=self.File_Struct(i) if i.is_dir() else i.name
        else:
            file_struct[a.name]=a.name
        return file_struct
    def Details(self,files):
        htmlelem=""
        if type(files)==type({}):
            #htmlelem+="<details>"
            for  i in files:
                if type(files[i])==type({}):

                    htmlelem+=f"<details data-name='{i}' data-type='folder' >"
                    htmlelem+=f"<summary>{i}</summary>"
                    htmlelem+=self.Details(files[i])+"</details>"
                else:
                    htmlelem+=f"<p data-name='{i}' data-type='file'>{i}</p>"
            #htmlelem+="</details>"
        return htmlelem
    def RunTerminal(self,path,command):
        file_read=""
        with open(path,"r") as f:
            file_read=f.read()
        
