<html>

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"
        integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@500&display=swap" rel="stylesheet">
</head>

<body>
    <table class="table table-hover">
        <thead>
            <tr class="table-dark">
                <th class="time" scope="col">Time</th>
                <th class="entry" scope="col">Entry</th>
                <th class="password" scope="col">Password</th>
                <th></th>
            </tr>
        </thead>

        <tbody>
            {% for item in items %}
            <tr>
                <td>{{ item.time }}</td>
                <td>
                    {% for e in item.entry %}
                    <button type="button" onclick="onEntryClicked(this)" class="btn btn-secondary">{{ e }}</button>
                    {% endfor %}
                </td>
                <td data="{{ item.data }}" class="overflow-x-auto">****</td>
                <td>
                    <button type="button" class="btn btn-dark" onclick="onCopyClicked(this)">copy</button>
                    <button type="button" class="btn btn-dark" onclick="onShowClicked(this)">show</button>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <!-- Modal -->
    <div class="modal fade" id="master-passwd-modal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5">please input master password</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="password" class="form-control" id="master-passwd" onkeydown="handleKeyDown(event)">
                </div>
                <div class="modal-footer">
                    <button type="button" id="master-passwd-ok" class="btn btn-primary">OK</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 在页面底部添加一个 Toasts 消息容器
    <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
        <div id="copy-toast" class="toast align-items-center text-white bg-success border-0" role="alert"
            aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">已复制</div>
                <button type="button" class="btn-close ms-auto me-2" data-bs-dismiss="toast"
                    aria-label="Close"></button>
            </div>
        </div>
    </div> -->

    <div class="toast-container border-0 position-fixed bottom-0 end-0 p-3">
        <div id="copy-toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-body">
                已复制
            </div>
        </div>
    </div>

    <script>
        var masterPassword = "";

        const passwdModal = new bootstrap.Modal('#master-passwd-modal', {
            keyboard: false
        })
        $('#master-passwd-modal').on('shown.bs.modal', function () {
            $('#master-passwd').focus();
        })

        var copyToast = new bootstrap.Toast(document.getElementById("copy-toast"));

        function handleKeyDown(event) {
            if (event.key === 'Enter') {
                $('#master-passwd-ok').click();
            }
        }

        function onEntryClicked(e) {
            copyText(e.innerText);
            copyToast.show();
        }

        async function onCopyClicked(btn) {
            let passwdElement = btn.parentElement.previousElementSibling;
            console.log("copy", passwdElement);
            let passwd = await decryptPasssword(passwdElement.getAttribute('data'));
            // navigator.clipboard.writeText(passwd);
            // copy password
            copyText(passwd);
            copyToast.show();
        }

        async function onShowClicked(btn) {
            let passwdElement = btn.parentElement.previousElementSibling;
            console.log(passwdElement);
            if (btn.innerText == "show") {
                let passwd = await decryptPasssword(passwdElement.getAttribute('data'));
                passwdElement.innerText = passwd;
                $(btn).text('hide');
                setTimeout(() => {
                    passwdElement.innerText = "****";
                    $(btn).text('show');
                }, 3000);
            } else {
                passwdElement.innerText = "****";
                $(btn).text('show');
            }
        }

        function onPasswdOkClicked(resolve) {
            let input = document.getElementById('master-passwd');
            if (input.value != '')
                masterPassword = input.value;
            resolve();
            input.value = '';
            passwdModal.hide();
        }

        async function getMasterPassword() {
            if (masterPassword != "") {
                return masterPassword;
            }
            let cnt = 0;
            let cb;
            let ele = document.getElementById('master-passwd-ok');
            while (masterPassword == "" && cnt < 2) {
                passwdModal.show();
                await new Promise(resolve => {
                    cb = function () { onPasswdOkClicked(resolve); };
                    ele.addEventListener('click', cb);
                })
                cnt++;
            }
            console.log('get master password', masterPassword);
            passwdModal.hide();
            if (masterPassword != "") {
                setTimeout(function () {
                    console.log("master password cleared");
                    masterPassword = "";
                    ele.removeEventListener('click', cb);
                }, 30000);
            }
            return masterPassword;
        }

        async function decryptPasssword(cipher) {
            let key = await getMasterPassword();
            let passwd = await new Promise(resolve => {
                $.ajax({
                    url: "/decrypt",
                    method: 'POST',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({
                        'data': cipher,
                        'passwd': key,
                    }),
                    statusCode: {
                        500: function () {
                            alert("wrong password");
                            masterPassword = '';
                        }
                    }
                }).done(function (data) {
                    resolve(data['data']);
                });
            });
            return passwd;
        }

        function copyText(text) {
            var textArea = document.createElement("textarea");
            textArea.value = text;

            var container = document.createElement("div");
            container.appendChild(textArea);

            document.body.appendChild(container);
            textArea.select();
            document.execCommand("copy");
            document.body.removeChild(container);
        }

    </script>

    <style>
        body {
            font-family: 'Inconsolata', monospace;
        }

        table {
            width: 100%;
            text-align: left;
        }

        th {
            padding: 10px !important;
            ;
        }

        thead {
            position: sticky;
            top: 0;
            font-size: x-large;
        }
    </style>
</body>

</html>