<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        body,
        html {
            height: 100%;
        }

        /* 
        #copyToken {
            transition: backgroundColor .3s;
        } */
    </style>
    <%- include('./partials/head') %>
    <title><%= config.meta.title %> - Dashboard</title>
</head>

<body>
    <div id="particles-js"></div>
    <div class="container h-100 d-flex justify-content-center">
        <div class="jumbotron my-auto">
            <ul class="nav nav-pills mb-3" id="main-view-tab-list" role="tablist">
                <li class="nav-item">
                    <a style="border-radius: 50px;" class="nav-link active" id="home-tab" data-toggle="tab" href="#home"
                        role="tab" aria-controls="home" aria-selected="true">Home</a>
                </li>
                <li class="nav-item">
                    <a style="border-radius: 50px;" class="nav-link" id="profile-tab" data-toggle="tab" href="#images"
                        role="tab" aria-controls="images" aria-selected="false">Your Images</a>
                </li>
                <% if (user.administrator) { %>
                <li class="nav-item">
                    <a style="border-radius: 50px;" class="nav-link" id="contact-tab" data-toggle="tab" href="#users"
                        role="tab" aria-controls="users" aria-selected="false">Users</a>
                </li>
                <% } %>
            </ul>
            <div class="tab-content" id="main-view">
                <div class="tab-pane fade show active m-3" id="home" role="tabpanel" aria-labelledby="home-tab">
                    <h2>Welcome back, <%= user.username %> <a class="btn btn-sm btn-danger" href="/logout"
                            style="border-radius: 50px;">Logout</a>
                    </h2>
                    <p>You have <b><%= images.length %></b> images saved, and you
                        <%= user.administrator ? 'are an administrator' : 'are not an administrator' %>.</p>
                    <h4>API Token</h4>
                    <button type="button" class="btn btn-sm btn-primary" id="copyToken"
                        style="border-radius: 50px;">Copy</button>
                    <button type="button" class="btn btn-sm btn-danger" id="regenToken"
                        style="border-radius: 50px;">Regenerate</button>
                    <h4 style="margin-top:12px">Update your Profile</h4>
                    <form>
                        <div class="form-group">
                            <label for="usernameSave">Username</label>
                            <input value="<%= user.username %>" type="text" class="form-control" id="usernameSave"
                                placeholder="Username">
                        </div>

                        <div class="form-group">
                            <label for="passwordSave">Password</label>
                            <input value="<%= user.password %>" type="password" class="form-control" id="passwordSave"
                                placeholder="Password">
                        </div>
                        <button type="button" class="btn btn-primary" id="saveUser"
                            style="border-radius: 50px; width:100%;">Save</button>
                    </form>
                </div>
                <div class="tab-pane fade m-3" id="images" role="tabpanel" aria-labelledby="images-tab">
                    <h3>Your Images</h3>
                    <table class="table">
                        <thead>
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">URL</th>
                                <th scope="col">Preview</th>
                            </tr>
                        </thead>
                        <tbody>
                            <% images.forEach(image => { %>
                            <tr>
                                <th scope="row"><%= image.id %></th>
                                <td><a href="<%= image.url %>"><%=image.url%></td>
                                <td><img src="<%= image.url %>" height="48"></td>
                            </tr>
                            <% }) %>
                        </tbody>
                    </table>
                </div>
                <% if (user.administrator) { %>
                <div class="tab-pane fade m-3" id="users" role="tabpanel" aria-labelledby="users-tab">
                    <table class="table">
                        <thead>
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">Username</th>
                                <th scope="col">Administrator</th>
                            </tr>
                        </thead>
                        <tbody>
                            <% users.forEach(u => { %>
                            <tr>
                                <th scope="row"><%= u.id %></th>
                                <td><%= u.username %></td>
                                <% if (u.administrator) { %>
                                <td class="text-success">Yes</td>
                                <% } else { %>
                                <td class="text-danger">No</td>
                                <% } %>
                                <td>
                                    <% if (!u.administrator) { %>
                                    <button type="button" class="btn  btn-sm btn-danger"
                                        style="border-radius: 50px;">Delete</button>
                                    <% } %>
                                </td>
                            </tr>
                            <% }); %>
                        </tbody>
                    </table>
                    <button style="border-radius: 50px;" type="button" class="btn btn-primary" data-toggle="modal"
                        data-target="#modal">Create new
                        User</button>
                    <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
                        aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="exampleModalLabel">New User</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <form>
                                        <div class="form-group">
                                            <label for="username">Username</label>
                                            <input type="text" class="form-control" id="username" name="username"
                                                placeholder="Username">
                                        </div>

                                        <div class="form-group">
                                            <label for="password">Password</label>
                                            <input type="password" class="form-control" id="password" name="password"
                                                placeholder="Password">
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="administrator">
                                                <label class="custom-control-label"
                                                    for="administrator">Administrator?</label>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <div class="row" style="width:100%;">
                                        <div class="col-sm-6">
                                            <button type="button" id="createUser" class="btn btn-primary"
                                                style="border-radius: 50px; width:100%;">Create</button>
                                        </div>
                                        <div class="col-sm-6">
                                            <button type="button" class="btn btn-danger" data-dismiss="modal"
                                                style="border-radius: 50px; width:100%;">Cancel</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <% } %>
            </div>
        </div>
    </div>
    <p style="display:none" id="partenabled"><%=config.particles.enabled%></p>
    <p style="display:none" id="part"><%=JSON.stringify(config.particles.settings) %></p>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@9/dist/sweetalert2.min.js"></script>
    <script src="http://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
    <script>if (document.getElementById('partenabled').innerText === "true") particlesJS("particles-js", JSON.parse(document.getElementById('part').innerText));</script>
    <script>
        function whitespace(str) {
            return str === null || str.match(/^ *$/) !== null;
        }

        function showAlert(type, message) {
            if (type === 'error') {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: message,
                    footer: 'Try again later...'
                })
            } else if (type === 'success') {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: message,
                    footer: 'You did it!'
                })
            }
        }

        document.getElementById('saveUser').addEventListener('click', async () => {
            Swal.fire({
                title: 'Are you sure?',
                text: "You are proceeding to edit your user.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, save changes!'
            }).then(async (result) => {
                if (result.value) {
                    const username = document.getElementById('usernameSave').value;
                    const password = document.getElementById('passwordSave').value;
                    if (whitespace(username)) return showAlert('error', 'Please input a username.')
                    const res = await fetch('/api/user', {
                        method: 'PATCH',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            username,
                            password
                        })
                    });
                    try {
                        const json = await res.json();
                        if (json.error || json.code) return showAlert('error', json.error)
                        else {
                            Swal.fire(
                                'Saved Changes!',
                                'Changes were saved successfully!',
                                'success'
                            );
                        }
                    } catch (e) {
                        console.error(e)
                    }
                }
            });
        });

        document.getElementById('copyToken').addEventListener('click', async () => {
            Swal.fire({
                title: 'Are you sure?',
                text: "You are proceeding to copy your token, make sure NO ONE sees it.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, copy it!'
            }).then((result) => {
                if (result.value) {
                    const el = document.createElement('textarea');
                    el.value = "<%= user.token %>";
                    document.body.appendChild(el);
                    el.select();
                    document.execCommand('copy');
                    document.body.removeChild(el);
                    Swal.fire(
                        'Copied!',
                        'Your API Token has been copied.',
                        'success'
                    );
                }
            });
        });
        document.getElementById('regenToken').addEventListener('click', async () => {
            Swal.fire({
                title: 'Are you sure?',
                text: "You are proceeding to regenerate your token, remember all apps using your current one will stop working.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, regenerate it!'
            }).then(async (result) => {
                if (result.value) {
                    const res = await fetch('/api/token', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    try {
                        const json = await res.json();
                        if (json.error || json.code) return showAlert('error', json.error)
                        else {
                            Swal.fire(
                                'Regenerated!',
                                'Your API Token has been regenerated.',
                                'success'
                            );
                            return window.location.href = '/'
                        }
                    } catch (e) {
                        console.error(e)
                    }

                }
            });

        })
        // async function editUser() {
        //     const username = document.getElementById('usernameEdit').value;
        //     const password = document.getElementById('passwordEdit').value;
        //     if (whitespace(username)) return showAlert('error', 'Please input a username.')
        //     const res = await fetch('/api/user', {
        //         method: 'PATCH',
        //         headers: {
        //             'Content-Type': 'application/json'
        //         },
        //         body: JSON.stringify({
        //             username,
        //             password,
        //             administrator: document.getElementById('administratorEdit').checked
        //         })
        //     });
        //     try {
        //         const json = await res.json();
        //         if (json.error || json.code) return showAlert('error', json.error)
        //         else {
        //             $('#edit-modal').modal('toggle');
        //             showAlert('success', `Edited user ${json.username} (${json.id})`)
        //             return window.location.href = '/'
        //         }
        //     } catch (e) {
        //         console.error(e)
        //     }
        // }
        // document.getElementById('editUser').addEventListener('click', async () => {
        //     if (document.getElementById('administratorEdit').checked) {
        //         Swal.fire({
        //             title: 'Are you sure?',
        //             text: "You are proceeding to save a user with administrator permissions, they can do whatever they want!",
        //             icon: 'warning',
        //             showCancelButton: true,
        //             confirmButtonColor: '#3085d6',
        //             cancelButtonColor: '#d33',
        //             confirmButtonText: 'Yes, edit user!'
        //         }).then(async (result) => {
        //             if (result.value) {
        //                 editUser()
        //             }
        //         });
        //     } else {
        //         editUser();
        //     }
        // })
        async function createUser() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            if (whitespace(username)) return showAlert('error', 'Please input a username.')
            const res = await fetch('/api/user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    password,
                    administrator: document.getElementById('administrator').checked
                })
            });
            try {
                const json = await res.json();
                if (json.error || json.code) return showAlert('error', json.error)
                else {
                    $('#modal').modal('toggle');
                    showAlert('success', `Created user ${json.username} (${json.id})`)
                    return window.location.href = '/'
                }
            } catch (e) {
                console.error(e)
            }
        }
        document.getElementById('createUser').addEventListener('click', async () => {
            if (document.getElementById('administrator').checked) {
                Swal.fire({
                    title: 'Are you sure?',
                    text: "You are proceeding to create a user with administrator permissions, they can do whatever they want!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, create user!'
                }).then(async (result) => {
                    if (result.value) {
                        createUser()
                    }
                });
            } else {
                createUser();
            }
        })
    </script>
</body>

</html>