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


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

script_dir = Path(__file__).parent
save_dir = script_dir.joinpath('../save').resolve()
# save_dir = 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 = {'list': [], 'tree': {}}
    for currentFile in save_dir.iterdir():
        if currentFile.is_file() and currentFile.name[-5:] == '.json':
            year, version, timestamp = currentFile.name[:-5].split("_")
            if year not in result['tree']:
                result['tree'][year] = {}
            if version not in result['tree'][year]:
                result['tree'][year][version] = []
            result['tree'][year][version].append(timestamp)
            result['list'].append({'year': year, 'version': version, 'timestamp': timestamp})
    return result


@app.route('/load/<year>/<version>/<timestamp>', methods=['GET'])
def load(year, version, timestamp):
    file = full_filename(year, version, timestamp)

    if not Path(file).exists():
        file_list = list_dict()
        timestamp = file_list['tree'][year][version][-1]
        file = full_filename(year, version, timestamp)

    print(file)
    time.sleep(2)
    return open(file, 'r').read()


def full_filename(year, version, timestamp):
    return f'{str(save_dir)}/{year}_{version}_{timestamp}.json'


@app.route('/load/<filename>', methods=['GET'])
def load_file(filename):
    full_filename = f'{str(save_dir)}/{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(save_dir) + '/' + 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(save_dir) + '/' + 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()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8082')
