from pathlib import Path
from flask import request, Flask
import json
from flask_cors import CORS
from datetime import datetime
import hashlib

app = Flask(__name__)
# cors = CORS(app, resources={r"/*": {"origins": "http://localhost:4200/"}})
CORS(app)

currentDirectory = Path('C:\\Projekte\\Python\\Planung\\save')


@app.route('/list/', methods=['GET'])
def list_json():
    return json.dumps(list_dict(), indent=2)


def list_dict():
    result = {}
    for currentFile in currentDirectory.iterdir():
        if currentFile.is_file() and currentFile.name[-5:] == '.json':
            name_split = currentFile.name[:-5].split("_")
            current_list = result.get(name_split[0], [])
            current_list.append(name_split[1])
            result[name_split[0]] = current_list
    return result


@app.route('/load/<filename>', methods=['GET'])
def load(filename):
    full_filename = f'{str(currentDirectory)}/{filename}.json'
    if not Path(full_filename).exists():
        file_list = list_dict()
        timestamp = file_list[filename][-1]
        full_filename = f'{full_filename[:-5]}_{timestamp}.json'

    print(full_filename)
    return open(full_filename, 'r').read()


@app.route('/save/<filename>', methods=['POST'])
def save(filename):
    if request.method != 'POST':
        return 'File is missing!'

    new_filename = str(currentDirectory) + '/' + filename + '_' + datetime.now().strftime('%Y%m%d%H%M%S') + '.json'
    data = request.get_json()['data']
    json.dump(data, open(new_filename, 'w'), indent=2)
    print(new_filename)

    try:
        file_list = list_dict()
        timestamp = file_list[filename][-2]
        old_filename = str(currentDirectory) + '/' + filename + "_" + timestamp + '.json'

        if old_filename != new_filename and hash(old_filename) == hash(new_filename):
            Path(old_filename).unlink()
            return 'File saved with no changes!'
    except KeyError:
        pass
    return 'File saved with new data!'


def hash(filename):
    BUF_SIZE = 65536
    sha1 = hashlib.sha1()
    with open(filename, 'rb') as g:
        while True:
            hashdata = g.read(BUF_SIZE)
            if not hashdata:
                break
            sha1.update(hashdata)
    return sha1.hexdigest()
