{% extends 'skillfarm/base.html' %}
{% load i18n %}
{% load humanize %}

{% block page_title %} Skillfarm Calculator{% endblock %}
{% block page_topic %}<h1 class="page-header text-center">{% translate "Skillfarm Calculator" %}</h1>{% endblock page_topic %}

{% block skillfarm_block %}
<div class="container-fluid">
    <div class="card-body">
        <div id="container">
            <div id="fieldcontents">
                {% if not error %}
                    <h5 class="border-bottom pb-2">
                        {% translate "Single Price" %}
                        <span class="text-muted float-end small">{% translate "last update" %}: {{ skillfarm.plex.updated_at }}</span>
                    </h5>
                    <ul class="price-list">
                        <li>
                            <span class="item-name">{{ skillfarm.injektor.eve_type.name }}:</span>
                            <span id="injektor" class="editable-click" data-original="{{ skillfarm.injektor.average_price|floatformat:0 }}" data-type="number" data-title="Enter value">{{ skillfarm.injektor.average_price|floatformat:0 }}</span><span class="px-2"> ISK</span>
                        </li>
                        <li>
                            <span class="item-name">{{ skillfarm.extratkor.eve_type.name }}:</span>
                            <span id="extratkor" class="editable-click" data-original="{{ skillfarm.extratkor.average_price|floatformat:0 }}" data-type="number" data-title="Enter value">{{ skillfarm.extratkor.average_price|floatformat:0 }}</span><span class="px-2"> ISK</span>
                        </li>
                        <li>
                            <span class="item-name">{{ skillfarm.plex.eve_type.name }}:</span>
                            <span id="plex" class="editable-click" data-original="{{ skillfarm.plex.average_price|floatformat:0 }}" data-type="number" data-title="Enter value">{{ skillfarm.plex.average_price|floatformat:0 }}</span><span class="px-2"> ISK</span>
                        </li>
                    </ul>
                    <h5 class="border-bottom pb-2">{% translate "Monthly Profit" %}
                        <button class="btn btn-sm btn-info btn-square" data-bs-toggle="popover" data-bs-content="Calculated with 3.5 Skill Injektors" data-bs-placement="top" data-bs-trigger="hover">
                            <span class="fas fa-info"></span>
                        </button>
                    </h5>
                    <ul class="price-list">
                        <li>
                            <span class="item-name">{% translate "Profit Month Abo" %}:</span>
                            <span id="plex" class="price {% if skillfarm.calc.month >= 0 %}text-success{% else %}text-danger{% endif %}">
                                {{ skillfarm.calc.month|floatformat:0|intcomma }} <span class="text-white">ISK</span>
                            </span>
                        </li>
                        <li>
                            <span class="item-name">{% translate "Profit 12 Month Abo" %}:</span>
                            <span id="plex" class="price {% if skillfarm.calc.month12 >= 0 %}text-success{% else %}text-danger{% endif %}">
                                {{ skillfarm.calc.month12|floatformat:0|intcomma }} <span class="text-white">ISK</span>
                            </span>
                        </li>
                        <li>
                            <span class="item-name">{% translate "Profit 24 Month Abo" %}:</span>
                            <span id="plex" class="price {% if skillfarm.calc.month24 >= 0 %}text-success{% else %}text-danger{% endif %}">
                                {{ skillfarm.calc.month24|floatformat:0|intcomma }} <span class="text-white">ISK</span>
                            </span>
                        </li>
                    </ul>
                    <div class="d-flex align-items-center">
                        <h2 class="mb-0">{% translate "Calculation" %}</h2>
                        <div class="ms-3">
                            <label for="duration" class="form-label d-inline"></label>
                            <select class="btn btn-secondary form-select d-inline w-auto" id="duration" required>
                                <option value="1">{% translate "Monthly" %}</option>
                                <option value="12">{% translate "12 Months" %}</option>
                                <option value="24">{% translate "24 Months" %}</option>
                            </select>
                        </div>
                    </div>
                    <form id="calculator-form">
                        <div class="row">
                            <div class="col-md-6 py-2">
                                <label for="injector-amount" class="form-label">{% translate "Skill Injector Amount" %}</label>
                                <input type="number" class="form-control" id="injector-amount">
                            </div>
                            <div class="col-md-6 py-2">
                                <label for="extractor-amount" class="form-label">{% translate "Skill Exctractor Amount" %}</label>
                                <input type="number" class="form-control" id="extractor-amount">
                            </div>
                        </div>
                        <div class="form-check py-2">
                            <input class="form-check-input" type="checkbox" id="custom-plex-checkbox">
                            <label class="form-check-label" for="custom-plex-checkbox">
                                {% translate "Use custom PLEX amount" %}
                            </label>
                        </div>
                        <div class="col-md-6 py-2" id="custom-plex-amount-container" style="display: none;">
                            <label for="custom-plex-amount" class="form-label">{% translate "Custom PLEX Amount" %}</label>
                            <input type="number" class="form-control" id="custom-plex-amount">
                        </div>
                        <button type="button" class="btn btn-primary" onclick="calculate()">{% translate "Calculate" %}</button>
                    </form>
                    <h3 id="result" class="mt-3"></h3>
                {% else %}
                    <span>
                        {% translate "An error occurred while fetching the market data. Please ensure that EveMarketPrice is updated. Please inform an admin." %}
                    </span>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_javascript %}
{% include 'skillfarm/bundles/x-editable.html' %}
<script>
document.addEventListener('DOMContentLoaded', function () {
    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
    var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl)
    })

    // Initialize X-Editable with jQuery UI
    $.fn.editable.defaults.mode = 'popup';
    $.fn.editable.defaults.ajaxOptions = { type: 'PUT' };
    $('.editable-click').editable({
        type: 'number',
        title: 'Enter value',
        placement: 'top',
        display: function(value) {
            // Display the value with thousands separators
            if (!value) {
                // Display the original value if the new value is empty
                value = $(this).data('original');
            } else {
                // Store the new value
                $(this).text(parseFloat(value).toLocaleString());
            }
        },
        success: function(response, newValue) {
            // Check if the new value is empty
            if (!newValue) {
                console.log('Empty value');
                // Revert to the original value
                const originalValue = $(this).data('original');
                $(this).text(parseFloat(originalValue).toLocaleString());
            } else {
                // Display the value with thousands separators after saving
                $(this).text(parseFloat(newValue).toLocaleString());
            }
            calculate();
        },
        inputclass: 'editable-input',
        onblur: 'submit'
    });

    // Remove thousands separators when the input field is shown
    $('.editable-click').on('shown', function(e, editable) {
        var value = $(this).text().replace(/[,.]/g, '');
        editable.input.$input.val(value);
    });

    // Other existing event listeners and functions
    document.getElementById('duration').addEventListener('change', function(event) {
        calculate();
    });

    document.getElementById('calculator-form').addEventListener('submit', function(event) {
        event.preventDefault();
        calculate();
    });

    document.getElementById('injector-amount').addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            calculate();
        }
    });

    document.getElementById('extractor-amount').addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            calculate();
        }
    });

    document.getElementById('custom-plex-amount').addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            calculate();
        }
    });

    document.getElementById('custom-plex-checkbox').addEventListener('change', function() {
        const customPlexAmountContainer = document.getElementById('custom-plex-amount-container');
        const durationSelect = document.getElementById('duration');
        if (this.checked) {
            customPlexAmountContainer.style.display = 'block';
            durationSelect.disabled = true;
        } else {
            customPlexAmountContainer.style.display = 'none';
            durationSelect.disabled = false;
        }
        calculate();
    });
});

function calculate() {
    const injectorAmount = parseFloat(document.getElementById('injector-amount').value) || 0;
    const extraktorAmount = parseFloat(document.getElementById('extractor-amount').value) || 0;
    const duration = parseInt(document.getElementById('duration').value);
    const useCustomPlex = document.getElementById('custom-plex-checkbox').checked;
    const customPlexAmount = parseFloat(document.getElementById('custom-plex-amount').value) || 0;

    if (injectorAmount === 0 && extraktorAmount === 0) {
        document.getElementById('result').innerHTML = `<span style="color: red;"> {% translate "Please fill out at least one field: Skill Injector or Extractor" %}</span>`;
        return;
    }

    // Get the prices from the editable fields or use the original values
    const injectorPrice = parseFloat(document.getElementById('injektor').innerText.replace(/[,.]/g, '')) || parseFloat({{ skillfarm.injektor.average_price }});
    const extraktorPrice = parseFloat(document.getElementById('extratkor').innerText.replace(/[,.]/g, '')) || parseFloat({{ skillfarm.extratkor.average_price }});
    const plexPrice = parseFloat(document.getElementById('plex').innerText.replace(/[,.]/g, '')) || parseFloat({{ skillfarm.plex.average_price }});

    const totalInjectorPrice = (injectorPrice * injectorAmount) - (extraktorPrice * extraktorAmount);

    let plexMultiplier;
    if (useCustomPlex) {
        plexMultiplier = customPlexAmount;
    } else {
        if (duration === 1) {
            plexMultiplier = 500;
        } else if (duration === 12) {
            plexMultiplier = 300;
        } else if (duration === 24) {
            plexMultiplier = 275;
        }
    }
    const totalPlexPrice = plexPrice * plexMultiplier;
    const totalPrice = totalInjectorPrice - totalPlexPrice;

    let resultText;
    resultText = `{% translate "Result" %}: <span style="color: ${totalPrice < 0 ? 'red' : 'green'};">${Math.round(totalPrice).toLocaleString()} ISK</span>`;

    document.getElementById('result').innerHTML = resultText;
}
</script>
{% endblock %}

{% block extra_css %}
<style>
    .price-list {
        list-style-type: none;
        padding: 0;
    }
    .price-list li {
        display: flex;
        justify-content: space-between;
    }
    .item-name {
        flex: 1;
    }
    .price {
        flex: 1;
        text-align: right;
        font-weight: bold;
    }
</style>
{% endblock %}

{% block extra_script %}
{% endblock %}
