from flask import Flask, request, jsonify, render_template
from datetime import datetime
import string
import auth

app_config = auth.return_app_config()

# Secret alphabet
ALPHABET = string.ascii_letters + string.digits


def folder_secret_config_editor():
    title_short = app_config.get('TITLE_SHORT', 'Default Title')
    title_long  = app_config.get('TITLE_LONG' , 'Default Title')
    return render_template('folder_secret_config_editor.html',
                           alphabet=ALPHABET,
                           admin_enabled=auth.is_admin(),
                           title_short=title_short,
                           title_long=title_long)


def folder_secret_config_action():
    p = request.get_json()
    data = auth.return_folder_config()
    action = p.get('action')
    if action == 'delete':
        data = [r for r in data if r['secret'] != p['secret']]
    elif action == 'update':
        old = p['oldSecret']; new = p['newSecret']
        for i, r in enumerate(data):
            if r['secret'] == old:
                r['secret'] = new
                r['validity'] = datetime.strptime(p['validity'], '%Y-%m-%d').strftime('%d.%m.%Y')
                r['folders'] = p['folders']
                break
        else:
            # append if not found
            data.append({
                'secret': new,
                'validity': datetime.strptime(p['validity'], '%Y-%m-%d').strftime('%d.%m.%Y'),
                'folders': p['folders']
            })
    auth.save_folder_config(data)
    return jsonify(success=True)

