"""
todo.py - a simple TODO app based on a Cloudomation webhook
"""

import uuid
import chevron
import flow_api


MAIN = '''
<html>
<head>
    <title>Cloudomation TODO</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        button {
            cursor: pointer;
            font-size: 20px;
        }
        input {
            font-size: 20px;
            padding: 0 10px;
        }
        .todo-list {
            display: flex;
            flex-direction: column;
            width: 500px;
            border: 1px solid lightgray;
            border-radius: 8px;
            background: lightyellow;
        }
        .todo-new {
            padding: 10px;
            display: flex;
            justify-content: space-between;
        }
        .todo-item {
            padding: 10px;
            border-top: 1px dashed gray;
            display: flex;
            justify-content: space-between;
        }
        .todo-label {
            border: 0;
            background-color: transparent;
        }
        .todo-label-done {
            text-decoration: line-through;
        }
    </style>
    <script>
        async function post(url, data) {
            return await fetch(
                url,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data),
                }
            );
        }

        const todoNew = () => {
            const newTodoLabel = document.getElementById("new-todo-label").value;
            post('', { 'action': 'todoNew', newTodoLabel })
                .then(() => {
                    window.location.reload();
                });
        };
        const todoDone = (id) => {
            post('', { 'action': 'todoDone', id })
                .then(() => {
                    window.location.reload();
                });
        };
        const todoUndone = (id) => {
            post('', { 'action': 'todoUndone', id })
                .then(() => {
                    window.location.reload();
                });
        };
        const todoRemove = (id) => {
            post('', { 'action': 'todoRemove', id })
                .then(() => {
                    window.location.reload();
                });
        };
    </script>
</head>
<body>
    <h1>Cloudomation TODO app</h1>
    {{#debug}}
    <pre>
method: {{method}}
json: {{json}}
path: {{path}}
query: {{query}}
    </pre>
    {{/debug}}
    <div class="todo-list">
        <div class="todo-new"><input type="text" id="new-todo-label" placeholder="What needs to be done?" />&nbsp;<button onclick="todoNew()">add</button></div>
        {{#todos}}
        <div class="todo-item">
            {{^done}}
            <button class="todo-label todo-label-todo" onclick="todoDone('{{id}}')">&#x2610; {{label}}</button>
            {{/done}}
            {{#done}}
            <button class="todo-label todo-label-done" onclick="todoUndone('{{id}}')">&#x2611; {{label}}</button>
            <button class="todo-remove" onclick="todoRemove('{{id}}')">remove</button>
            {{/done}}
        </div>
        {{/todos}}
    </div>
    <div>{{count}} TODOs</div>
</body>
</html>
'''


def handler(system: flow_api.System, this: flow_api.Execution):
    inputs = this.get('input_value')
    method = inputs['method']

    store = system.setting('todo-store')
    try:
        todos = store.get('value')
    except flow_api.ResourceNotFoundError:
        todos = []
    if not todos:
        todos = []

    if method == 'POST':
        json = inputs['json']
        action = json.get('action')
        if action == 'todoNew':
            todos.append({
                'id': str(uuid.uuid4()),
                'label': json['newTodoLabel'],
            })
        elif action == 'todoDone':
            todos = [
                {
                    **todo,
                    'done': True,
                }
                if todo['id'] == json['id'] else todo
                for todo
                in todos
            ]
        elif action == 'todoUndone':
            todos = [
                {
                    **todo,
                    'done': False,
                }
                if todo['id'] == json['id'] else todo
                for todo
                in todos
            ]
        elif action == 'todoRemove':
            todos = [
                todo
                for todo
                in todos
                if todo['id'] != json['id']
            ]

        store.save(value=todos)
        return this.success('all done')


    data = {
        'count': len(todos),
        'todos': todos,
    }

    return this.webhook_html_response(
        chevron.render(MAIN, data)
    )
