"""
Generates update scripts to patch files
"""

from diff_match_patch import diff_match_patch
import os.path
import os
from ..local import DotConfigFiles

diff_match_patch = diff_match_patch()

TEMPLATE = """
# GENERATED BY PATCHER.py
# Patches files {}
from diff_match_patch import diff_match_patch
diff_match_patch = diff_match_patch()

patches = {}

for f in patches:
    with open(f[0], "r") as re:
        text = re.read()
    text, results = diff_match_patch.patch_apply(diff_match_patch.patch_fromText(f[1]), text)
    if not all(results):
        raise ValueError('''file differs to much from original''')
    with open(f[0], "w") as wi:
        wi.write(text)
    print("Updated " + f[0])
"""

TEMPLATE_WRITE = """
# GENERATED BY PATCHER.py
# Creates files {}
import os

files = {}

for f, c in files:
    if not os.path.exists(os.path.dirname(f)) and os.path.dirname(f) != "":
        os.makedirs(os.path.dirname(f))
        print("Created directory " + os.path.dirname(f))
    with open(f, "w") as wi:
        wi.write(c)
print("Create files")
"""

def create_template_write(db: DotConfigFiles, file_array):
    """
    Create a write script for files created
    """

    home_dir = os.path.dirname(db.load_file)
    files = []

    for f in file_array:
        p = os.path.join(home_dir, f)
        with open(p, "r") as g:
            files.append((f, g.read()))

    files = repr(files)

    return TEMPLATE_WRITE.format(repr(file_array), files)

def create_template_update(db: DotConfigFiles, file_array):
    """
    Create a patch script
    """

    home_dir = os.path.dirname(db.load_file)
    files = []

    for f in file_array:
        entry = [f, None]
        with db.filemon.open_version(f, "r") as original, open(os.path.join(home_dir, f), "r") as newer:
            orig = original.read().decode("utf-8")
            new  = newer.read()

            diffs = diff_match_patch.diff_main(orig, new)
            print(diffs)
            diff_match_patch.diff_cleanupSemantic(diffs)

            entry[1] = diff_match_patch.patch_make(orig, diffs)
            entry[1] = diff_match_patch.patch_toText(entry[1])
        files.append(entry)

    files = repr(files)

    return TEMPLATE.format(repr(file_array), files)
