{% extends "secrets/secret_addedit.html" %}
{% load i18n %}
{% load django_bootstrap5 %}
{% block content_type_fields %}
    <div class="row mb-3 {% if not form.password.errors and form.is_bound %}is-valid{% endif %}">
        <div class="col-xl-2">
            <label class="col-form-label securely-saved" for="{{ form.password.id_for_label }}">
                {% translate "Password" %}
            </label>
        </div>
        <div class="col-xl-8">
            <div class="input-group">
                <input class="form-control {% if not form.password.errors and form.is_bound %}is-valid{% endif %}"
                       id="{{ form.password.id_for_label }}" name="{{ form.password.name }}"
                       placeholder="{% if secret %}{% trans "(unchanged)" %}{% else %}**************{% endif %}"
                       {% if not secret %}required="required"{% endif %} type="password" autocomplete="off"
                       {% if form.is_bound and not secret %}value="{{ form.password.value }}"{% endif %}>

                <span class="input-group-text" title="{% trans "Password strength" %}" id="id_password_strength">
                    {% for i in '12345'|make_list %}
                        <i class="far fa-star text-muted"></i>
                    {% endfor %}
                </span>
                <button class="btn border btn-light" id="id_pwgen" type="button"
                        title="{% trans "Generate random password" %}">
                    <i class="fa fa-refresh fa-fw align-middle text-body"></i>
                </button>
            </div>
        </div>
    </div>
    <div class="row {% if form.otp_key_data.errors %}mb-1{% else %}mb-3{% endif %}">
        <div class="col-xl-2">
            <label class="col-form-label securely-saved" for="{{ form.otp_key.id_for_label }}">
                {% translate "OTP secret key" %}
            </label>
        </div>
        <div class="col-xl-8">
            <div class="input-group">
                <input class="form-control {% if form.otp_key_data.errors %}is-invalid{% elif form.is_bound %}is-valid{% endif %}"
                       id="{{ form.otp_key.id_for_label }}" type="text"
                       placeholder="{% if current_revision.otp_key_set %}{% trans "(unchanged)" %}
                                    {% else %}{% trans "enter OTP secret key" %}{% endif %}">
                <input type="hidden" class="form-control" id="{{ form.otp_key_data.id_for_label }}"
                       name="{{ form.otp_key_data.name }}" value="">
                <canvas id="canvas" style="display: none;"></canvas>
                <button class="btn border btn-light" id="key-input-type" type="button"
                        title="{% trans "Switch to enter OTP key as QR image or paste from clipboard" %}"
                        data-bs-toggle="tooltip">
                    <i class="fa fa-qrcode fa-fw align-middle"></i>
                </button>
                {% for text in form.otp_key_data.errors %}
                    <div class="invalid-feedback">{{ text }}</div>
                {% endfor %}
            </div>
        </div>
    </div>
    {% bootstrap_field form.username placeholder="(optional)" layout="horizontal" label_class="searchable" %}
    {% bootstrap_field form.url placeholder="(optional)" layout="horizontal" label_class="searchable" %}
{% endblock %}

{% block additionalJS %}
    {{ block.super }}
    <script>
        const passwordField = document.getElementById('id_password')
        const passwordGeneratorField = document.getElementById('id_pwgen')
        const passwordStrengthField = document.getElementById('id_password_strength')
        const otpField = document.getElementById('{{ form.otp_key.id_for_label }}')
        const otpKeyData = document.getElementById('{{ form.otp_key_data.id_for_label }}')
        const typeBtn = document.getElementById('key-input-type')

        passwordField.generated = false

        function ratePassword() {
            let score = zxcvbn(passwordField.value.toString()).score + 1;
            let color = "text-warning-bright";
            if (!passwordField.value) {
                color = "text-muted";
                score = 0;
            } else if (score <= 2) {
                color = "text-danger-bright";
            } else if (score === 5) {
                color = "text-success-bright";
            }
            var filled_star = `<i class='fas fa-star ${color}'></i>`;
            var hollow_star = `<i class='far fa-star ${color}'></i>`;
            passwordStrengthField.innerHTML = filled_star.repeat(score) + hollow_star.repeat(5 - score)
        }

        async function generatePassword() {
            const source = await fetch('{% url 'api.generate-password' %}');
            return source.json();
        }

        function keyInputText() {
            let typeBtnTooltip = bootstrap.Tooltip.getInstance('#key-input-type')
            typeBtnTooltip.setContent({
                '.tooltip-inner':
                    '{% trans "Switch to enter OTP key as plain text" %}'
            })

            const typeBtn = document.getElementById('key-input-type');
            typeBtn.querySelector('i').classList.remove('fa-qrcode')
            typeBtn.querySelector('i').classList.add('fa-keyboard')
            otpField.title = "Enter OTP key as QR image or paste from clipboard"
            otpField.type = "file"
        }

        function keyInputQr() {
            let typeBtnTooltip = bootstrap.Tooltip.getInstance('#key-input-type')
            typeBtnTooltip.setContent({
                '.tooltip-inner':
                    '{% trans "Switch to enter OTP key as QR image or paste from clipboard" %}'
            })
            const typeBtn = document.getElementById('key-input-type');
            typeBtn.querySelector('i').classList.remove('fa-keyboard')
            typeBtn.querySelector('i').classList.add('fa-qrcode')
            otpField.title = "Enter OTP secret key manually"
            otpField.type = "text"
        }

        document.addEventListener('paste', e => {
            if (otpField.type === "file") {
                otpField.files = e.clipboardData.files;
                otpField.dispatchEvent(new Event('change'));
            }
        })

        document.addEventListener('submit', () => {
            if (otpField.value && !otpKeyData.value) {
                let data = otpField.value;
                if (!data.includes('?secret=')) {
                    data = '?secret=' + data + '&';
                }
                if (!data.includes('digits=')) {
                    data += 'digits=6&';
                }
                if (!data.includes('algorithm=')) {
                    data += 'algorithm=SHA1&';
                }
                otpKeyData.value = data;
            }
        })

        document.addEventListener('DOMContentLoaded', () => {
            ratePassword();
        })

        otpField.addEventListener('change', () => {
            if (otpField.type !== "file") {
                return;
            }
            const file = otpField.files[0];
            if (!file) {
                return;
            }
            const reader = new FileReader();
            reader.onload = function (event) {
                const img = new Image();
                img.onload = function () {
                    const canvas = document.getElementById('canvas');
                    const ctx = canvas.getContext('2d');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.fillStyle = "rgb(255, 255, 255)"
                    ctx.fillRect(0, 0, canvas.width, canvas.height)
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                    try {
                        const code = qrScanner(imageData.data, imageData.width, imageData.height);
                        keyInputQr();
                        let data = new URL(code.data.toString());
                        otpKeyData.value = data;
                        otpField.value = data.searchParams.get('secret');
                    } catch (e) {
                        keyInputText()
                        window.notyf.error("Error. No QR code found. Please try again.")
                    }
                };
                img.src = event.target.result;
            };
            reader.readAsDataURL(file);
        })

        passwordField.addEventListener('keyup', () => {
            ratePassword();
            passwordField.generated = false;
            setTimeout(function () {
                    if (!passwordField.generated) {
                        passwordField.type = 'password'
                    }
                },
                2000
            );
        })
        passwordGeneratorField.addEventListener('focusout', () => {
            setTimeout(
                function () {
                    if (document.activeElement !== passwordField) {
                        passwordField.type = 'password';
                    }
                },
                1000
            )
        })
        passwordGeneratorField.addEventListener('click', async () => {
            passwordField.value = await generatePassword();
            ratePassword();
            passwordField.type = 'text';
            passwordField.generated = true;
        })
        typeBtn.addEventListener("click", () => {
            if (otpField.type === "file") {
                keyInputQr();
            } else {
                keyInputText();
            }
        })
    </script>
{% endblock %}
