{% extends "base.jinja2" %}

{% block page_title %}
    {{ title }}
{% endblock %}

{% block jumbotron %}
    <h1>{{ website.page_title }}</h1>
    <p>{{ website.page_headline }}</p>
{% endblock %}

{% block content %}
    <div class="row">
        <div class="col-md-4">
            <fieldset class="form-group">
                <div class="card-group" id="accordion">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header" id="headingLabelSize">
                                <h4 class="card-title">
                                    <button class="btn" data-bs-toggle="collapse" data-bs-target="#collapseLabelSize" aria-expanded="false" aria-controls="collapseLabelSize">
                                        <span class="bi-file-earmark-fill" aria-hidden="true"></span> Label Size
                                    </button>
                                </h4>
                            </div>
                            <div id="collapseLabelSize" class="collapse" aria-labelledby="headingLabelSize" data-parent="#accordion">
                                <div class="chooser card-body">
                                    <label for="labelSize" style="display: none">Label Size:</label>
                                    <select class="form-control" id="labelSize" onChange="preview()">
                                            {% for label_size in label_sizes %}<option value="{{label_size[0]}}" {% if label.default_size == label_size[0] %}selected{% endif %}>{{label_size[1]}}</option>{% endfor %}
                                        </select>
                                    <label for="orientation" style="margin-top: 10px; margin-bottom: 0">Label Orientation:</label>
                                    <div class="radio" style="margin-top: 5px;">
                                        <label><input type="radio" onchange="preview()" name="orientation" value="standard" {% if default_orientation == 'standard' %}checked{% endif %}>Standard</label>
                                    </div>
                                    <div class="radio">
                                        <label><input type="radio" onchange="preview()" name="orientation" value="rotated" {% if default_orientation == 'rotated' %}checked{% endif %}>Rotated</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title" id="headingFontSettings">
                                    <button class="btn" data-bs-toggle="collapse" data-bs-target="#collapseFontSettings" aria-expanded="true" aria-controls="collapseFontSettings">
                                        <span class="bi-fonts" aria-hidden="true"></span> Font Settings
                                    </button>
                                </h4>
                            </div>
                            <div id="collapseFontSettings" class="collapse show" aria-labelledby="headingFontSettings" data-parent="#accordion">
                                <div class="chooser card-body">
                                    <label for="fontFamily">Font Family:</label>
                                    <select class="form-control" id="fontFamily" onChange="preview()">
                                        {% for font_family_name in font_family_names %}
                                            {% for font_style in fonts[font_family_name].keys() %}
                                        <option {% if label.default_font.style == font_style and label.default_font.family == font_family_name %}selected{% endif %}>{{font_family_name}} ({{ font_style }})</option>
                                            {% endfor %}
                                        {% endfor %}
                                    </select>
                                    <label for="fontSize">Font Size:</label>
                                    <input id="fontSize" class="form-control" type="number" min="1" value="{{ label.default_font_size }}" onChange="preview()" required>
                                    <label for="fontAlign" class="control-label input-group">Font Alignment:</label>
                                    <div class="btn-group" data-toggle="buttons">
                                        <label class="btn btn-default">
                                            <input type="radio" name="fontAlign" onchange="preview()" value="left" aria-label="Left Align"><span class="bi-text-left" aria-hidden="true"></span>
                                        </label>
                                        <label class="btn btn-default active">
                                            <input type="radio" name="fontAlign" onchange="preview()" value="center" aria-label="Center Align" checked=""><span class="bi-text-center" aria-hidden="true"></span>
                                        </label>
                                        <label class="btn btn-default">
                                            <input type="radio" name="fontAlign" onchange="preview()" value="right" aria-label="Right Align"><span class="bi-text-right" aria-hidden="true"></span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header" id="headingDetailedSettings">
                                <h4 class="card-title">
                                    <button class="btn" data-bs-toggle="collapse" data-bs-target="#collapseDetailedSettings" aria-expanded="false" aria-controls="collapseDetailedSettings">
                                        <span class="bi-gear-fill" aria-hidden="true"></span> Detailed Settings
                                    </button>
                                </h4>
                            </div>
                            <div id="collapseDetailedSettings" class="collapse" aria-labelledby="headingDetailedSettings" data-parent="#accordion">
                                <div class="chooser card-body">
                                    <label for="marginTop">Margin Top:</label>
                                    <div class="input-group marginsTopBottom">
                                        <input id="marginTop" class="form-control marginsTopBottom" type="number" min="0" max="200" value="24" onChange="preview()" required> <span class="input-group-addon">%</span>
                                    </div>
                                    <label for="marginBottom">Margin Bottom:</label>
                                    <div class="input-group marginsTopBottom">
                                        <input id="marginBottom" class="form-control marginsTopBottom" type="number" min="0" max="200" value="45" onChange="preview()" required> <span class="input-group-addon">%</span>
                                    </div>
                                    <label for="marginLeft">Margin Left:</label>
                                    <div class="input-group marginsLeftRight">
                                        <input id="marginLeft" class="form-control marginsLeftRight" type="number" min="0" max="200" value="35" onChange="preview()" required> <span class="input-group-addon">%</span>
                                    </div>
                                    <label for="marginRight">Margin Right:</label>
                                    <div class="input-group marginsLeftRight">
                                        <input id="marginRight" class="form-control marginsLeftRight" type="number" min="0" max="200" value="35" onChange="preview()" required> <span class="input-group-addon">%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header" id="headingAmount">
                            <h4 class="card-title">
                                <button class="btn" data-bs-toggle="collapse" data-bs-target="#collapseAmount" aria-expanded="false" aria-controls="collapseAmount">
                                    <span class="bi-repeat" aria-hidden="true"></span> Amount
                                </a>
                            </h4>
                        </div>
                        <div id="collapseAmount" class="collapse" aria-labelledby="headingAmount" data-parent="#accordion">
                            <div class="chooser card-body">
                                <label for="labelCount">Label Count:</label>
                                <div class="input-group labelCount">
                                    <input id="labelCount" class="form-control" type="number" min="1" max="200" value="1" required>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header" id="headingQuality">
                            <h4 class="card-title">
                                <button class="btn" data-bs-toggle="collapse" data-bs-target="#collapseQuality" aria-expanded="false" aria-controls="collapseQuality">
                                    <span class="bi-badge-hd-fill" aria-hidden="true"></span> Quality
                                </a>
                            </h4>
                        </div>
                        <div id="collapseQuality" class="collapse" aria-labelledby="headingQuality" data-parent="#accordion">
                            <div class="chooser card-body">
                                <label class="btn">
                                    <input type="checkbox" name="highQuality" id="highQuality" onchange="preview()" aria-label="High Quality" checked="checked"> High Quality
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>
        </div>
        <div class="col-md-4">
            <fieldset class="form-group">
                <label for="labelText">Label Text:</label>
                <textarea rows="7" id="labelText" class="form-control" onChange="preview()" onInput="preview()"></textarea>
            </fieldset>
        </div>
        <div class="col-md-4">
            <fieldset class="form-group">
                <label for="previewImg">Label Preview:</label><br />
                <img id="previewImg" style="border: 1px solid #444; max-height: 350px; width: auto; max-width: 100%; margin-bottom: 10px;" />
                <p>Printed size w/o margins: <span id="labelWidth">?</span> cm x <span id="labelHeight">?</span> cm</p>
                <button id="printButton" type="button" class="btn btn-primary btn-block btn-lg" onClick="print()">
              <span class="bi-printer-fill" aria-hidden="true"></span> Print
            </button>
            </fieldset>
            <div class="card card-default">
                <div class="card-header">
                    <h3 class="card-title"><span class="bi-journal" aria-hidden="true" style="margin-right: 0.3em"></span> Status</h3>
                </div>
                <div id="statusPanel" class="card-body">
                    - undefined -
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block javascript %}
    function getValue(id) {
        return document.getElementById(id).value;
    }

    function getSelectedOption(id) {
        const selection = document.getElementById(id);
        return selection.options[selection.selectedIndex].value;
    }

    function getSelectedRadioButton(name, fallback) {
        const selector = document.querySelector('input[name="' + name + '"]:checked');
        if (!selector) {
            return fallback;
        }
        return selector.value;
    }

    function isChecked(id) {
        return document.getElementById(id).checked;
    }

    function formData() {
        var text = getValue('labelText');
        if (text == '') {
            text = ' ';
        }
        const fontFamily = getSelectedOption('fontFamily');
        const fontSize = getValue('fontSize');
        const labelSize = getSelectedOption('labelSize');
        const align = getSelectedRadioButton('fontAlign', 'center');
        const orientation = getSelectedRadioButton('orientation', 'standard');
        const marginTop = getValue('marginTop');
        const marginBottom = getValue('marginBottom');
        const marginLeft = getValue('marginLeft');
        const marginRight = getValue('marginRight');
        const labelCount = getValue('labelCount');
        const highQuality = isChecked('highQuality');

        const data = new FormData();
        data.append('text', text);
        data.append('font_family', fontFamily);
        data.append('font_size', fontSize);
        data.append('label_size', labelSize);
        data.append('align', align);
        data.append('orientation', orientation);
        data.append('margin_top', marginTop);
        data.append('margin_bottom', marginBottom);
        data.append('margin_left', marginLeft);
        data.append('margin_right', marginRight);
        data.append('label_count', labelCount);
        data.append('high_quality', highQuality);
        return data;
    }

    function setPreviewImage(response) {
        const img = document.getElementById('previewImg');
        img.setAttribute('src', 'data:image/png;base64,' + response.response);
        img.onload = function() {
            document.getElementById('labelWidth').innerHTML = (img.naturalWidth / 300 * 2.54).toFixed(1);
            document.getElementById('labelHeight').innerHTML = (img.naturalHeight /300 * 2.54).toFixed(1);
        };
    }

    function preview() {
        const marginsTopBottom = document.getElementsByClassName('marginsTopBottom');
        const marginsLeftRight = document.getElementsByClassName('marginsLeftRight');

        function enable(elements) {
            for (const element of elements) {
                element.removeAttribute('disabled');
                element.removeAttribute('title');
            }
        }

        function disable(elements, orientation) {
            for (const element of elements) {
                element.disabled = true;
                element.setAttribute('title', 'Only relevant if ' + orientation + ' orientation is selected.');
            }
        }

        if (getSelectedRadioButton('orientation', 'standard') == 'standard') {
            enable(marginsTopBottom);
            disable(marginsLeftRight, 'rotated');
        } else {
            enable(marginsLeftRight);
            disable(marginsTopBottom, 'standard');
        }

        const request = new XMLHttpRequest();
        request.addEventListener('load', function() {
            setPreviewImage(this);
        });
        request.open('POST', '/api/preview/text?return_format=base64');
        request.setRequestHeader('Accept', 'application/x-www-form-urlencoded; charset=UTF-8');
        request.send(formData());
    }

    function setStatus(data) {
        if (data.success) {
            document.getElementById('statusPanel').innerHTML = '<div id="statusBox" class="alert alert-success" role="alert"><i class="bi-check-square"></i><span>Printing was successful.</span></div>';
        } else {
            /* TODO: https://developer.mozilla.org/en-US/docs/Web/API/Element/setHTML#browser_compatibility */
            document.getElementById('statusPanel').innerHTML = '<div id="statusBox" class="alert alert-warning" role="alert"><i class="bi-exclamation-triangle-fill"></i><span>Printing was unsuccessful:<br />' + data.message + '</span></div>';
        }
        document.getElementById('printButton').removeAttribute('disabled');
    }

    function print() {
        document.getElementById('printButton').setAttribute('disabled', true);
        document.getElementById('statusPanel').innerHTML = '<div id="statusBox" class="alert alert-info" role="alert"><i class="bi-hourglass"></i><span>Processing print request...</span></div>';

        const request = new XMLHttpRequest();
        request.addEventListener('load', function() {
            setStatus(JSON.parse(this.response));
        });
        request.addEventListener('error', function() {
            setStatus(JSON.parse(this.response));
        });
        request.open('POST', '/api/print/text');
        request.setRequestHeader('Accept', 'application/x-www-form-urlencoded; charset=UTF-8');
        request.send(formData());
    }

    preview();

{% endblock %}
