import os
import shutil


def mod_img_dir(mdfilename, oldphrase, newphrase):
    oldphrase = oldphrase[:-3]
    oldphrase = oldphrase.replace(" ", "%20")
    newphrase = "../assets/blogs/" + newphrase

    with open(mdfilename, "r") as f:
        content = f.read()
        content = content.replace(oldphrase, newphrase)
    with open(mdfilename, "w") as f:
        f.write(content)


with open("tools/temp/unzip.log", "r") as file:
    for line in file:
        if "filename" in line:
            cols = line.split(" ")
            filename = cols[1][0:-4]
        elif "inflating: " in line:
            line = line.strip("\n ")
            cols = line.split("/")
            if ".md" in line:
                oldpath = cols[1:]
                oldpath = "/"+os.path.join(*oldpath)
                newpath = cols[1:-1] + [filename+".md"]
                newpath = "/"+os.path.join(*newpath)
                shutil.move(oldpath, newpath)
                mod_img_dir(newpath, cols[-1], filename)
            elif ".png" in line:
                oldpath = cols[1:-1] + [""]
                oldpath = "/"+os.path.join(*oldpath)
                newpath = cols[1:-3] + ["assets", "blogs", filename, ""]
                newpath = "/"+os.path.join(*newpath)
                shutil.move(oldpath, newpath)
                break
