<!DOCTYPE html>
<html lang="en" dir="ltr" id="main_html">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8" />
        <title id="title">User</title>
        <!-- Material Icons -->
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
        <!-- Material Symbols - Outlined Set -->
        <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet" />
        <!-- Material Symbols - Rounded Set -->
        <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded" rel="stylesheet" />
        <!-- Material Symbols - Sharp Set -->
        <link rel="stylesheet" href="{{ url_for('static', filename='css/uikit.min.css') }}"/>
        <link rel="stylesheet" href="{{ url_for('static', filename='css/pantry.css') }}"/>

        <link id="dark-mode" rel="stylesheet" href="{{ url_for('static', filename='css/dark-mode.css') }}" disabled/>
    </head>
    <body>
        <div class="uk-section">
            <div class="uk-container uk-container-xsmall">
                <div class="uk-grid-small" uk-grid>
                    <div class="uk-width-1-1" >
                        <a href="/admin" class="uk-button uk-button-small"><span class="uk-flex material-symbols-outlined">arrow_back</span></a>
                        <a onclick="toggleDarkMode()" class="uk-button uk-button-small uk-align-right"><span id="modeToggle" class="uk-flex material-symbols-outlined">dark_mode</span></a>
                    </div>
                    <div class="uk-width-1-1">
                        <h3 class="uk-text-center">User/Device Form</h3>
                    </div>
                    <div class="uk-width-1-1">
                        <p>Users and Devices, better known as access points, are credentials to acccess the system from specific areas. Users are intended to be
                            you basic login for actual people. Devices are created when you know a the credentials are to be used in one place and no where else.
                            Differentiating between the two is helpful to see who by/where in your setup transactions are happening.</p>
                    </div>
                    <div class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="login_name">Access Name</label>
                            <div class="uk-form-controls">
                                <input class="uk-input" id="login_name" type="text">
                            </div>
                        </div>
                    </div>
                    <div class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="login_email">Access Email</label>
                            <div class="uk-form-controls">
                                <input class="uk-input" id="login_email" type="text">
                            </div>
                        </div>
                    </div>
                    <div class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="login_type">Access Type</label>
                            <div class="uk-form-controls">
                                <select class="uk-select" id="login_type">
                                    <option value="user">User</option>
                                    <option value="device">Device</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="uk-width-1-1">
                        <hr class="uk-divider-icon">
                    </div>
                    <div id="new_password" class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="new_login_password">Access Password</label>
                            <div class="uk-form-controls">
                                <input class="uk-input" id="new_login_password" type="password">
                            </div>
                        </div>
                    </div>
                    <div id="new_password" class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="new_login_password_retype">Access Retype Password</label>
                            <div class="uk-form-controls">
                                <input class="uk-input" id="new_login_password_retype" type="password">
                            </div>
                        </div>
                    </div>
                    <div id="old_password" class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="old_login_password">Current Access Password</label>
                            <div class="uk-form-controls">
                                <input class="uk-input" id="old_login_password" type="password">
                            </div>
                        </div>
                    </div>
                    <div id="old_password" class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="old_login_password_new">New Access Password</label>
                            <div class="uk-form-controls">
                                <input class="uk-input" id="old_login_password_new" type="password">
                            </div>
                        </div>
                    </div>
                    <div id="old_password" class="uk-width-1-1">
                        <div class="uk-margin">
                            <label class="uk-form-label" for="old_login_password_new_retype">Retype New Access Password</label>
                            <div class="uk-form-controls">
                                <input class="uk-input" id="old_login_password_new_retype" type="password">
                            </div>
                        </div>
                    </div>
                    <div id="old_password" class="uk-width-1-1">
                        <button onclick="postEditLoginPassword()" class="uk-button uk-button-primary uk-align-right">Update Password</button>
                    </div>
                    <div class="uk-width-1-1">
                        <hr class="uk-divider-icon">
                    </div>
                    <div class="uk-width-1-1">
                        <caption>These are the Sites this access point has permission to see</caption>
                        <table class="uk-table uk-table-striped uk-table-small">
                            <thead>
                                <tr>
                                    <th class="uk-text-center">Site Name</th>
                                    <th class="uk-text-center">Operations</th>
                                </tr>
                            </thead>
                            <tbody id="sitesTableBody">
                                <tr>
                                    <td class="uk-text-center">Test</td>
                                    <td class="uk-text-center"><button class="uk-button uk-button-small uk-button-default">Remove</button></td>
                                </tr>
                                <tr>
                                    <td class="uk-text-center">Test</td>
                                    <td class="uk-text-center"><button class="uk-button uk-button-small uk-button-default">Remove</button></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="uk-width-1-1">
                        <caption>These are the roles that the access point has in each permissable site</caption>
                        <table class="uk-table uk-table-striped uk-table-small">
                            <thead>
                                <tr>
                                    <th class="uk-text-center">Site Role</th>
                                    <th class="uk-text-center">Operations</th>
                                </tr>
                            </thead>
                            <tbody id="siteRolesTableBody">
                                <tr>
                                    <td class="uk-text-center">Test</td>
                                    <td class="uk-text-center"><button class="uk-button uk-button-small uk-button-default">Remove</button></td>
                                </tr>
                                <tr>
                                    <td class="uk-text-center">Test</td>
                                    <td class="uk-text-center"><button class="uk-button uk-button-small uk-button-default">Remove</button></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="uk-width-1-1">
                        <hr class="uk-divider-icon">
                    </div>
                    <div class="uk-width-1-1">
                        <button id="SubmitButton" class="uk-button uk-button-primary uk-align-right">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </body>
    {% assets "js_all" %}
    <script type="text/javascript" src="{{ ASSET_URL }}"></script>
    {% endassets %}
    <script>
        const user = {{user|tojson}}
        const session = {{session|tojson}}
        const path = window.location.pathname
    </script>
    <script>
        var update = {
            username: "",
            password: "",
            row_type: "",
            sites: [],
            site_roles: [],
            system_admin: false,
            flags: {
                permissions: {
                    sitename: {
                        items: {'nav': true, 'edit': false, 'view': true, 'delete': false},
                        item:{'nav': true, 'edit': false, 'view': true, 'delete': false},
                        recipes: {'nav': true, 'edit': false, 'view': true, 'delete': false},
                        receipts: {'nav': true, 'edit': false, 'view': true, 'delete': false},
                        shopping_lists: {'nav': true, 'edit': false, 'view': true, 'delete': false}
                    }
                },
                darkmode: true, // prefers dark mode
                solarized: false // preferse solarized 
            }
        }
        document.addEventListener('DOMContentLoaded', async function() {
            let mode = "edit"
            if(path == "/admin/user/new"){
                mode = "new"
            }
            console.log(user)
            await replenishForm(user, mode)
        })

        var mode = false
        async function toggleDarkMode() {
            let darkMode = document.getElementById("dark-mode");    
            darkMode.disabled = !darkMode.disabled;
            mode = !mode;
            if(mode){
                document.getElementById('modeToggle').innerHTML = "light_mode"
                document.getElementById('main_html').classList.add('uk-light')
            } else {
                document.getElementById('modeToggle').innerHTML = "dark_mode"
                document.getElementById('main_html').classList.remove('uk-light')
            }
        }

        if(session.user.flags.darkmode){
            toggleDarkMode()
        }

        async function replenishForm(user, mode){
            document.getElementById('login_name').value = user.username
            document.getElementById('login_email').value = user.email
            document.getElementById('login_type').value = user.row_type

            if(mode=="new"){
                document.querySelectorAll('#new_password').forEach(function(element) {
                    element.hidden = false;
                });
                document.querySelectorAll('#old_password').forEach(function(element) {
                    element.hidden = true;
                });
                document.getElementById('SubmitButton').innerHTML = "Add User"
                document.getElementById('SubmitButton').onclick = async function(){
                    await postAddLogin()
                }
            } else {
                document.querySelectorAll('#new_password').forEach(function(element) {
                    element.hidden = true;
                });
                document.querySelectorAll('#old_password').forEach(function(element) {
                    element.hidden = false;
                });
                document.getElementById('SubmitButton').innerHTML = "Update User"
                document.getElementById('SubmitButton').onclick = async function(){
                    await postEditLogin()
                }
            }
        }


        async function postAddLogin(){
            
            let payload = {
                username: document.getElementById('login_name').value,
                email: document.getElementById('login_email').value,
                password: document.getElementById('new_login_password').value,
                row_type: document.getElementById('login_type').value,
            }

            const response = await fetch(`/admin/user/postAddLogin`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    payload: payload
                }),
            });
            data =  await response.json();
            let transaction_status = "success"
            if (data.error){
                transaction_status = "danger"
                UIkit.notification({
                    message: data.message,
                    status: transaction_status,
                    pos: 'bottom-left',
                    timeout: 5000
                });
            } else {
                window.location.href = `/admin/user/${data.user.id}`
            }
        }

        async function postEditLoginPassword(){
            let payload = {
                id: user.id,
                current_password: document.getElementById('old_login_password').value,
                update: {password: document.getElementById('old_login_password_new').value}
            }

            const response = await fetch(`/admin/user/postEditLoginPassword`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    payload: payload
                }),
            });
            data =  await response.json();
            transaction_status = "success"
            if (data.error){
                transaction_status = "danger"
                UIkit.notification({
                    message: data.message,
                    status: transaction_status,
                    pos: 'bottom-left',
                    timeout: 5000
                });
                document.getElementById('old_login_password').classList.add('uk-form-danger')
                document.getElementById('old_login_password_new').classList.add('uk-form-danger')
                document.getElementById('old_login_password_new_retype').classList.add('uk-form-danger')
            } else {
                UIkit.notification({
                    message: data.message,
                    status: transaction_status,
                    pos: 'bottom-left',
                    timeout: 5000
                });
                document.getElementById('old_login_password').classList.remove('uk-form-danger')
                document.getElementById('old_login_password_new').classList.remove('uk-form-danger')
                document.getElementById('old_login_password_new_retype').classList.remove('uk-form-danger')
                document.getElementById('old_login_password').value = ""
                document.getElementById('old_login_password_new').value = ""
                document.getElementById('old_login_password_new_retype').value = ""
            }
        }

        async function postEditLogin(){
            let payload = {
                id: user.id,
                update: {
                    row_type: document.getElementById('login_type').value,
                    username: document.getElementById('login_name').value,
                    email: document.getElementById('login_email').value
                }
            }

            const response = await fetch(`/admin/user/postEditLogin`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    payload: payload
                }),
            });
            data =  await response.json();
            if (data.error){
                transaction_status = "danger"
                UIkit.notification({
                    message: data.message,
                    status: transaction_status,
                    pos: 'bottom-left',
                    timeout: 5000
                });
            } else {
                UIkit.notification({
                    message: data.message,
                    status: transaction_status,
                    pos: 'bottom-left',
                    timeout: 5000
                });
            }
        }

    </script>
</html>
